RequestGroup.cc 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "RequestGroup.h"
  36. #include <cassert>
  37. #include <algorithm>
  38. #include "PostDownloadHandler.h"
  39. #include "DownloadEngine.h"
  40. #include "SegmentMan.h"
  41. #include "NullProgressInfoFile.h"
  42. #include "Dependency.h"
  43. #include "prefs.h"
  44. #include "CreateRequestCommand.h"
  45. #include "File.h"
  46. #include "message.h"
  47. #include "util.h"
  48. #include "LogFactory.h"
  49. #include "Logger.h"
  50. #include "DiskAdaptor.h"
  51. #include "DiskWriterFactory.h"
  52. #include "RecoverableException.h"
  53. #include "StreamCheckIntegrityEntry.h"
  54. #include "CheckIntegrityCommand.h"
  55. #include "UnknownLengthPieceStorage.h"
  56. #include "DownloadContext.h"
  57. #include "DlAbortEx.h"
  58. #include "DownloadFailureException.h"
  59. #include "RequestGroupMan.h"
  60. #include "DefaultBtProgressInfoFile.h"
  61. #include "DefaultPieceStorage.h"
  62. #include "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. (downloadContext_->getTotalLength() > 0 ||
  509. downloadContext_->hasAttribute(bittorrent::BITTORRENT))) {
  510. #ifdef ENABLE_BITTORRENT
  511. SharedHandle<DefaultPieceStorage> ps
  512. (new DefaultPieceStorage(downloadContext_, option_.get()));
  513. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  514. if(isUriSuppliedForRequsetFileEntry
  515. (downloadContext_->getFileEntries().begin(),
  516. downloadContext_->getFileEntries().end())) {
  517. // Use LongestSequencePieceSelector when HTTP/FTP/BitTorrent
  518. // integrated downloads. Currently multi-file integrated
  519. // download is not supported.
  520. if(logger_->debug()) {
  521. logger_->debug("Using LongestSequencePieceSelector");
  522. }
  523. ps->setPieceSelector
  524. (SharedHandle<PieceSelector>(new LongestSequencePieceSelector()));
  525. }
  526. if(option_->defined(PREF_BT_PRIORITIZE_PIECE)) {
  527. std::vector<size_t> result;
  528. util::parsePrioritizePieceRange
  529. (result, option_->get(PREF_BT_PRIORITIZE_PIECE),
  530. downloadContext_->getFileEntries(),
  531. downloadContext_->getPieceLength());
  532. if(!result.empty()) {
  533. std::random_shuffle(result.begin(), result.end(),
  534. *(SimpleRandomizer::getInstance().get()));
  535. SharedHandle<PriorityPieceSelector> priSelector
  536. (new PriorityPieceSelector(ps->getPieceSelector()));
  537. priSelector->setPriorityPiece(result.begin(), result.end());
  538. ps->setPieceSelector(priSelector);
  539. }
  540. }
  541. }
  542. #else // !ENABLE_BITTORRENT
  543. SharedHandle<DefaultPieceStorage> ps
  544. (new DefaultPieceStorage(downloadContext_, option_.get()));
  545. #endif // !ENABLE_BITTORRENT
  546. if(!diskWriterFactory_.isNull()) {
  547. ps->setDiskWriterFactory(diskWriterFactory_);
  548. }
  549. tempPieceStorage = ps;
  550. } else {
  551. UnknownLengthPieceStorageHandle ps
  552. (new UnknownLengthPieceStorage(downloadContext_, option_.get()));
  553. if(!diskWriterFactory_.isNull()) {
  554. ps->setDiskWriterFactory(diskWriterFactory_);
  555. }
  556. tempPieceStorage = ps;
  557. }
  558. tempPieceStorage->initStorage();
  559. SharedHandle<SegmentMan> tempSegmentMan
  560. (new SegmentMan(option_.get(), downloadContext_, tempPieceStorage));
  561. pieceStorage_ = tempPieceStorage;
  562. segmentMan_ = tempSegmentMan;
  563. }
  564. void RequestGroup::dropPieceStorage()
  565. {
  566. segmentMan_.reset();
  567. pieceStorage_.reset();
  568. }
  569. bool RequestGroup::downloadFinishedByFileLength()
  570. {
  571. // assuming that a control file doesn't exist.
  572. if(!isPreLocalFileCheckEnabled() ||
  573. option_->getAsBool(PREF_ALLOW_OVERWRITE) ||
  574. (option_->getAsBool(PREF_CHECK_INTEGRITY) &&
  575. !downloadContext_->getPieceHashes().empty())) {
  576. return false;
  577. }
  578. if(!downloadContext_->knowsTotalLength()) {
  579. return false;
  580. }
  581. File outfile(getFirstFilePath());
  582. if(outfile.exists() && downloadContext_->getTotalLength() == outfile.size()) {
  583. return true;
  584. } else {
  585. return false;
  586. }
  587. }
  588. void RequestGroup::adjustFilename
  589. (const SharedHandle<BtProgressInfoFile>& infoFile)
  590. {
  591. if(!isPreLocalFileCheckEnabled()) {
  592. // OK, no need to care about filename.
  593. return;
  594. }
  595. if(!option_->getAsBool(PREF_DRY_RUN) &&
  596. option_->getAsBool(PREF_REMOVE_CONTROL_FILE) &&
  597. infoFile->exists()) {
  598. infoFile->removeFile();
  599. logger_->notice("Removed control file for %s because it is requested by"
  600. " user.", infoFile->getFilename().c_str());
  601. }
  602. if(infoFile->exists()) {
  603. // Use current filename
  604. } else if(downloadFinishedByFileLength()) {
  605. // File was downloaded already, no need to change file name.
  606. } else {
  607. File outfile(getFirstFilePath());
  608. if(outfile.exists() && option_->getAsBool(PREF_CONTINUE) &&
  609. outfile.size() <= downloadContext_->getTotalLength()) {
  610. // File exists but user decided to resume it.
  611. } else {
  612. #ifdef ENABLE_MESSAGE_DIGEST
  613. if(outfile.exists() && option_->getAsBool(PREF_CHECK_INTEGRITY)) {
  614. // check-integrity existing file
  615. } else {
  616. #endif // ENABLE_MESSAGE_DIGEST
  617. shouldCancelDownloadForSafety();
  618. #ifdef ENABLE_MESSAGE_DIGEST
  619. }
  620. #endif // ENABLE_MESSAGE_DIGEST
  621. }
  622. }
  623. }
  624. void RequestGroup::removeDefunctControlFile
  625. (const SharedHandle<BtProgressInfoFile>& progressInfoFile)
  626. {
  627. // Remove the control file if download file doesn't exist
  628. if(progressInfoFile->exists() &&
  629. !pieceStorage_->getDiskAdaptor()->fileExists()) {
  630. progressInfoFile->removeFile();
  631. logger_->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  632. progressInfoFile->getFilename().c_str(),
  633. downloadContext_->getBasePath().c_str());
  634. }
  635. }
  636. void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoFile)
  637. {
  638. try {
  639. if(!isPreLocalFileCheckEnabled()) {
  640. pieceStorage_->getDiskAdaptor()->initAndOpenFile();
  641. return;
  642. }
  643. removeDefunctControlFile(progressInfoFile);
  644. if(progressInfoFile->exists()) {
  645. progressInfoFile->load();
  646. pieceStorage_->getDiskAdaptor()->openExistingFile();
  647. } else {
  648. File outfile(getFirstFilePath());
  649. if(outfile.exists() && option_->getAsBool(PREF_CONTINUE) &&
  650. outfile.size() <= getTotalLength()) {
  651. pieceStorage_->getDiskAdaptor()->openExistingFile();
  652. pieceStorage_->markPiecesDone(outfile.size());
  653. } else {
  654. #ifdef ENABLE_MESSAGE_DIGEST
  655. if(outfile.exists() && option_->getAsBool(PREF_CHECK_INTEGRITY)) {
  656. pieceStorage_->getDiskAdaptor()->openExistingFile();
  657. } else {
  658. #endif // ENABLE_MESSAGE_DIGEST
  659. pieceStorage_->getDiskAdaptor()->initAndOpenFile();
  660. #ifdef ENABLE_MESSAGE_DIGEST
  661. }
  662. #endif // ENABLE_MESSAGE_DIGEST
  663. }
  664. }
  665. setProgressInfoFile(progressInfoFile);
  666. } catch(RecoverableException& e) {
  667. throw DOWNLOAD_FAILURE_EXCEPTION2
  668. (StringFormat(EX_DOWNLOAD_ABORTED).str(), e);
  669. }
  670. }
  671. // assuming that a control file does not exist
  672. void RequestGroup::shouldCancelDownloadForSafety()
  673. {
  674. if(option_->getAsBool(PREF_ALLOW_OVERWRITE)) {
  675. return;
  676. }
  677. File outfile(getFirstFilePath());
  678. if(outfile.exists()) {
  679. if(option_->getAsBool(PREF_AUTO_FILE_RENAMING)) {
  680. if(tryAutoFileRenaming()) {
  681. logger_->notice(MSG_FILE_RENAMED, getFirstFilePath().c_str());
  682. } else {
  683. throw DOWNLOAD_FAILURE_EXCEPTION
  684. (StringFormat("File renaming failed: %s",
  685. getFirstFilePath().c_str()).str());
  686. }
  687. } else {
  688. throw DOWNLOAD_FAILURE_EXCEPTION
  689. (StringFormat(MSG_FILE_ALREADY_EXISTS,
  690. getFirstFilePath().c_str()).str());
  691. }
  692. }
  693. }
  694. bool RequestGroup::tryAutoFileRenaming()
  695. {
  696. std::string filepath = getFirstFilePath();
  697. if(filepath.empty()) {
  698. return false;
  699. }
  700. for(unsigned int i = 1; i < 10000; ++i) {
  701. File newfile(strconcat(filepath, A2STR::DOT_C, util::uitos(i)));
  702. File ctrlfile(newfile.getPath()+DefaultBtProgressInfoFile::getSuffix());
  703. if(!newfile.exists() || (newfile.exists() && ctrlfile.exists())) {
  704. downloadContext_->getFirstFileEntry()->setPath(newfile.getPath());
  705. return true;
  706. }
  707. }
  708. return false;
  709. }
  710. void RequestGroup::createNextCommandWithAdj(std::vector<Command*>& commands,
  711. DownloadEngine* e, int numAdj)
  712. {
  713. int numCommand;
  714. if(getTotalLength() == 0) {
  715. numCommand = 1+numAdj;
  716. } else {
  717. numCommand = std::min(downloadContext_->getNumPieces(),
  718. numConcurrentCommand_);
  719. numCommand += numAdj;
  720. }
  721. if(numCommand > 0) {
  722. createNextCommand(commands, e, numCommand);
  723. }
  724. }
  725. void RequestGroup::createNextCommand(std::vector<Command*>& commands,
  726. DownloadEngine* e)
  727. {
  728. int numCommand;
  729. if(getTotalLength() == 0) {
  730. if(numStreamCommand_ > 0) {
  731. numCommand = 0;
  732. } else {
  733. numCommand = 1;
  734. }
  735. } else {
  736. if(numStreamCommand_ >= numConcurrentCommand_) {
  737. numCommand = 0;
  738. } else {
  739. numCommand = std::min(downloadContext_->getNumPieces(),
  740. numConcurrentCommand_-numStreamCommand_);
  741. }
  742. }
  743. if(numCommand > 0) {
  744. createNextCommand(commands, e, numCommand);
  745. }
  746. }
  747. void RequestGroup::createNextCommand(std::vector<Command*>& commands,
  748. DownloadEngine* e,
  749. unsigned int numCommand)
  750. {
  751. for(; numCommand--; ) {
  752. Command* command = new CreateRequestCommand(e->newCUID(), this, e);
  753. commands.push_back(command);
  754. }
  755. if(!commands.empty()) {
  756. e->setNoWait(true);
  757. }
  758. }
  759. std::string RequestGroup::getFirstFilePath() const
  760. {
  761. assert(!downloadContext_.isNull());
  762. if(inMemoryDownload()) {
  763. static const std::string DIR_MEMORY("[MEMORY]");
  764. return DIR_MEMORY+File(downloadContext_->getFirstFileEntry()->getPath()).getBasename();
  765. } else {
  766. return downloadContext_->getFirstFileEntry()->getPath();
  767. }
  768. }
  769. uint64_t RequestGroup::getTotalLength() const
  770. {
  771. if(pieceStorage_.isNull()) {
  772. return 0;
  773. } else {
  774. if(pieceStorage_->isSelectiveDownloadingMode()) {
  775. return pieceStorage_->getFilteredTotalLength();
  776. } else {
  777. return pieceStorage_->getTotalLength();
  778. }
  779. }
  780. }
  781. uint64_t RequestGroup::getCompletedLength() const
  782. {
  783. if(pieceStorage_.isNull()) {
  784. return 0;
  785. } else {
  786. if(pieceStorage_->isSelectiveDownloadingMode()) {
  787. return pieceStorage_->getFilteredCompletedLength();
  788. } else {
  789. return pieceStorage_->getCompletedLength();
  790. }
  791. }
  792. }
  793. void RequestGroup::validateFilename(const std::string& expectedFilename,
  794. const std::string& actualFilename) const
  795. {
  796. if(expectedFilename.empty()) {
  797. return;
  798. }
  799. if(expectedFilename != actualFilename) {
  800. throw DL_ABORT_EX(StringFormat(EX_FILENAME_MISMATCH,
  801. expectedFilename.c_str(),
  802. actualFilename.c_str()).str());
  803. }
  804. }
  805. void RequestGroup::validateTotalLength(uint64_t expectedTotalLength,
  806. uint64_t actualTotalLength) const
  807. {
  808. if(expectedTotalLength <= 0) {
  809. return;
  810. }
  811. if(expectedTotalLength != actualTotalLength) {
  812. throw DL_ABORT_EX
  813. (StringFormat(EX_SIZE_MISMATCH,
  814. util::itos(expectedTotalLength, true).c_str(),
  815. util::itos(actualTotalLength, true).c_str()).str());
  816. }
  817. }
  818. void RequestGroup::validateFilename(const std::string& actualFilename) const
  819. {
  820. validateFilename(downloadContext_->getFileEntries().front()->getBasename(), actualFilename);
  821. }
  822. void RequestGroup::validateTotalLength(uint64_t actualTotalLength) const
  823. {
  824. validateTotalLength(getTotalLength(), actualTotalLength);
  825. }
  826. void RequestGroup::increaseStreamCommand()
  827. {
  828. ++numStreamCommand_;
  829. }
  830. void RequestGroup::decreaseStreamCommand()
  831. {
  832. --numStreamCommand_;
  833. }
  834. void RequestGroup::increaseStreamConnection()
  835. {
  836. ++numStreamConnection_;
  837. }
  838. void RequestGroup::decreaseStreamConnection()
  839. {
  840. --numStreamConnection_;
  841. }
  842. unsigned int RequestGroup::getNumConnection() const
  843. {
  844. unsigned int numConnection = numStreamConnection_;
  845. #ifdef ENABLE_BITTORRENT
  846. if(!btRuntime_.isNull()) {
  847. numConnection += btRuntime_->getConnections();
  848. }
  849. #endif // ENABLE_BITTORRENT
  850. return numConnection;
  851. }
  852. void RequestGroup::increaseNumCommand()
  853. {
  854. ++numCommand_;
  855. }
  856. void RequestGroup::decreaseNumCommand()
  857. {
  858. --numCommand_;
  859. if(!numCommand_ && requestGroupMan_) {
  860. if(logger_->debug()) {
  861. logger_->debug("GID#%s - Request queue check", util::itos(gid_).c_str());
  862. }
  863. requestGroupMan_->requestQueueCheck();
  864. }
  865. }
  866. TransferStat RequestGroup::calculateStat() const
  867. {
  868. TransferStat stat;
  869. #ifdef ENABLE_BITTORRENT
  870. if(!peerStorage_.isNull()) {
  871. stat = peerStorage_->calculateStat();
  872. }
  873. #endif // ENABLE_BITTORRENT
  874. if(!segmentMan_.isNull()) {
  875. stat.setDownloadSpeed
  876. (stat.getDownloadSpeed()+segmentMan_->calculateDownloadSpeed());
  877. stat.setSessionDownloadLength
  878. (stat.getSessionDownloadLength()+
  879. segmentMan_->calculateSessionDownloadLength());
  880. }
  881. return stat;
  882. }
  883. void RequestGroup::setHaltRequested(bool f, HaltReason haltReason)
  884. {
  885. haltRequested_ = f;
  886. if(haltRequested_) {
  887. pauseRequested_ = false;
  888. haltReason_ = haltReason;
  889. }
  890. #ifdef ENABLE_BITTORRENT
  891. if(!btRuntime_.isNull()) {
  892. btRuntime_->setHalt(f);
  893. }
  894. #endif // ENABLE_BITTORRENT
  895. }
  896. void RequestGroup::setForceHaltRequested(bool f, HaltReason haltReason)
  897. {
  898. setHaltRequested(f, haltReason);
  899. forceHaltRequested_ = f;
  900. }
  901. void RequestGroup::setPauseRequested(bool f)
  902. {
  903. pauseRequested_ = f;
  904. }
  905. void RequestGroup::releaseRuntimeResource(DownloadEngine* e)
  906. {
  907. #ifdef ENABLE_BITTORRENT
  908. e->getBtRegistry()->remove(gid_);
  909. #endif // ENABLE_BITTORRENT
  910. if(!pieceStorage_.isNull()) {
  911. pieceStorage_->removeAdvertisedPiece(0);
  912. }
  913. // Don't reset segmentMan_ and pieceStorage_ here to provide
  914. // progress information via XML-RPC
  915. progressInfoFile_.reset();
  916. downloadContext_->releaseRuntimeResource();
  917. }
  918. void RequestGroup::preDownloadProcessing()
  919. {
  920. if(logger_->debug()) {
  921. logger_->debug("Finding PreDownloadHandler for path %s.",
  922. getFirstFilePath().c_str());
  923. }
  924. try {
  925. for(std::vector<SharedHandle<PreDownloadHandler> >::const_iterator itr =
  926. preDownloadHandlers_.begin(), eoi = preDownloadHandlers_.end();
  927. itr != eoi; ++itr) {
  928. if((*itr)->canHandle(this)) {
  929. (*itr)->execute(this);
  930. return;
  931. }
  932. }
  933. } catch(RecoverableException& ex) {
  934. logger_->error(EX_EXCEPTION_CAUGHT, ex);
  935. return;
  936. }
  937. if(logger_->debug()) {
  938. logger_->debug("No PreDownloadHandler found.");
  939. }
  940. return;
  941. }
  942. void RequestGroup::postDownloadProcessing
  943. (std::vector<SharedHandle<RequestGroup> >& groups)
  944. {
  945. if(logger_->debug()) {
  946. logger_->debug("Finding PostDownloadHandler for path %s.",
  947. getFirstFilePath().c_str());
  948. }
  949. try {
  950. for(std::vector<SharedHandle<PostDownloadHandler> >::const_iterator itr =
  951. postDownloadHandlers_.begin(), eoi = postDownloadHandlers_.end();
  952. itr != eoi; ++itr) {
  953. if((*itr)->canHandle(this)) {
  954. (*itr)->getNextRequestGroups(groups, this);
  955. return;
  956. }
  957. }
  958. } catch(RecoverableException& ex) {
  959. logger_->error(EX_EXCEPTION_CAUGHT, ex);
  960. }
  961. if(logger_->debug()) {
  962. logger_->debug("No PostDownloadHandler found.");
  963. }
  964. }
  965. void RequestGroup::initializePreDownloadHandler()
  966. {
  967. #ifdef ENABLE_BITTORRENT
  968. if(option_->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  969. preDownloadHandlers_.push_back(DownloadHandlerFactory::getBtPreDownloadHandler());
  970. }
  971. #endif // ENABLE_BITTORRENT
  972. #ifdef ENABLE_METALINK
  973. if(option_->get(PREF_FOLLOW_METALINK) == V_MEM) {
  974. preDownloadHandlers_.push_back(DownloadHandlerFactory::getMetalinkPreDownloadHandler());
  975. }
  976. #endif // ENABLE_METALINK
  977. }
  978. void RequestGroup::initializePostDownloadHandler()
  979. {
  980. #ifdef ENABLE_BITTORRENT
  981. if(option_->getAsBool(PREF_FOLLOW_TORRENT) ||
  982. option_->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  983. postDownloadHandlers_.push_back(DownloadHandlerFactory::getBtPostDownloadHandler());
  984. }
  985. #endif // ENABLE_BITTORRENT
  986. #ifdef ENABLE_METALINK
  987. if(option_->getAsBool(PREF_FOLLOW_METALINK) ||
  988. option_->get(PREF_FOLLOW_METALINK) == V_MEM) {
  989. postDownloadHandlers_.push_back(DownloadHandlerFactory::getMetalinkPostDownloadHandler());
  990. }
  991. #endif // ENABLE_METALINK
  992. }
  993. bool RequestGroup::isDependencyResolved()
  994. {
  995. if(dependency_.isNull()) {
  996. return true;
  997. }
  998. return dependency_->resolve();
  999. }
  1000. void RequestGroup::dependsOn(const DependencyHandle& dep)
  1001. {
  1002. dependency_ = dep;
  1003. }
  1004. void RequestGroup::setDiskWriterFactory(const DiskWriterFactoryHandle& diskWriterFactory)
  1005. {
  1006. diskWriterFactory_ = diskWriterFactory;
  1007. }
  1008. void RequestGroup::addPostDownloadHandler
  1009. (const SharedHandle<PostDownloadHandler>& handler)
  1010. {
  1011. postDownloadHandlers_.push_back(handler);
  1012. }
  1013. void RequestGroup::addPreDownloadHandler
  1014. (const SharedHandle<PreDownloadHandler>& handler)
  1015. {
  1016. preDownloadHandlers_.push_back(handler);
  1017. }
  1018. void RequestGroup::clearPostDownloadHandler()
  1019. {
  1020. postDownloadHandlers_.clear();
  1021. }
  1022. void RequestGroup::clearPreDownloadHandler()
  1023. {
  1024. preDownloadHandlers_.clear();
  1025. }
  1026. void RequestGroup::setPieceStorage(const PieceStorageHandle& pieceStorage)
  1027. {
  1028. pieceStorage_ = pieceStorage;
  1029. }
  1030. void RequestGroup::setProgressInfoFile(const BtProgressInfoFileHandle& progressInfoFile)
  1031. {
  1032. progressInfoFile_ = progressInfoFile;
  1033. }
  1034. bool RequestGroup::needsFileAllocation() const
  1035. {
  1036. return isFileAllocationEnabled() &&
  1037. (uint64_t)option_->getAsLLInt(PREF_NO_FILE_ALLOCATION_LIMIT) <= getTotalLength() &&
  1038. !pieceStorage_->getDiskAdaptor()->fileAllocationIterator()->finished();
  1039. }
  1040. DownloadResultHandle RequestGroup::createDownloadResult() const
  1041. {
  1042. if(logger_->debug()) {
  1043. logger_->debug("GID#%s - Creating DownloadResult.",
  1044. util::itos(gid_).c_str());
  1045. }
  1046. TransferStat st = calculateStat();
  1047. SharedHandle<DownloadResult> res(new DownloadResult());
  1048. res->gid = gid_;
  1049. res->fileEntries = downloadContext_->getFileEntries();
  1050. res->inMemoryDownload = inMemoryDownload_;
  1051. res->sessionDownloadLength = st.getSessionDownloadLength();
  1052. res->sessionTime = downloadContext_->calculateSessionTime();
  1053. res->result = downloadResult();
  1054. res->followedBy = followedByGIDs_;
  1055. res->belongsTo = belongsToGID_;
  1056. res->option = option_;
  1057. res->metadataInfo = metadataInfo_;
  1058. res->totalLength = getTotalLength();
  1059. res->completedLength = getCompletedLength();
  1060. res->uploadLength = st.getAllTimeUploadLength();
  1061. if(!pieceStorage_.isNull()) {
  1062. if(pieceStorage_->getBitfieldLength() > 0) {
  1063. res->bitfieldStr = util::toHex(pieceStorage_->getBitfield(),
  1064. pieceStorage_->getBitfieldLength());
  1065. }
  1066. }
  1067. #ifdef ENABLE_BITTORRENT
  1068. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  1069. res->infoHashStr = bittorrent::getInfoHashString(downloadContext_);
  1070. }
  1071. #endif // ENABLE_BITTORRENT
  1072. res->pieceLength = downloadContext_->getPieceLength();
  1073. res->numPieces = downloadContext_->getNumPieces();
  1074. res->dir = downloadContext_->getDir();
  1075. return res;
  1076. }
  1077. void RequestGroup::reportDownloadFinished()
  1078. {
  1079. logger_->notice(MSG_FILE_DOWNLOAD_COMPLETED,
  1080. downloadContext_->getBasePath().c_str());
  1081. uriSelector_->resetCounters();
  1082. #ifdef ENABLE_BITTORRENT
  1083. if(downloadContext_->hasAttribute(bittorrent::BITTORRENT)) {
  1084. TransferStat stat = calculateStat();
  1085. double shareRatio =
  1086. ((stat.getAllTimeUploadLength()*10)/getCompletedLength())/10.0;
  1087. SharedHandle<TorrentAttribute> attrs =
  1088. bittorrent::getTorrentAttrs(downloadContext_);
  1089. if(!attrs->metadata.empty()) {
  1090. logger_->notice(MSG_SHARE_RATIO_REPORT,
  1091. shareRatio,
  1092. util::abbrevSize(stat.getAllTimeUploadLength()).c_str(),
  1093. util::abbrevSize(getCompletedLength()).c_str());
  1094. }
  1095. }
  1096. #endif // ENABLE_BITTORRENT
  1097. }
  1098. void RequestGroup::addAcceptType(const std::string& type)
  1099. {
  1100. if(std::find(acceptTypes_.begin(), acceptTypes_.end(), type) == acceptTypes_.end()) {
  1101. acceptTypes_.push_back(type);
  1102. }
  1103. }
  1104. void RequestGroup::removeAcceptType(const std::string& type)
  1105. {
  1106. acceptTypes_.erase(std::remove(acceptTypes_.begin(), acceptTypes_.end(), type),
  1107. acceptTypes_.end());
  1108. }
  1109. void RequestGroup::setURISelector(const SharedHandle<URISelector>& uriSelector)
  1110. {
  1111. uriSelector_ = uriSelector;
  1112. }
  1113. void RequestGroup::applyLastModifiedTimeToLocalFiles()
  1114. {
  1115. if(!pieceStorage_.isNull() && lastModifiedTime_.good()) {
  1116. time_t t = lastModifiedTime_.getTime();
  1117. logger_->info("Applying Last-Modified time: %s in local time zone",
  1118. ctime(&t));
  1119. size_t n =
  1120. pieceStorage_->getDiskAdaptor()->utime(Time(), lastModifiedTime_);
  1121. logger_->info("Last-Modified attrs of %lu files were updated.",
  1122. static_cast<unsigned long>(n));
  1123. }
  1124. }
  1125. void RequestGroup::updateLastModifiedTime(const Time& time)
  1126. {
  1127. if(time.good() && lastModifiedTime_ < time) {
  1128. lastModifiedTime_ = time;
  1129. }
  1130. }
  1131. void RequestGroup::increaseAndValidateFileNotFoundCount()
  1132. {
  1133. ++fileNotFoundCount_;
  1134. const unsigned int maxCount = option_->getAsInt(PREF_MAX_FILE_NOT_FOUND);
  1135. if(maxCount > 0 && fileNotFoundCount_ >= maxCount &&
  1136. (segmentMan_.isNull() ||
  1137. segmentMan_->calculateSessionDownloadLength() == 0)) {
  1138. throw DOWNLOAD_FAILURE_EXCEPTION2
  1139. (StringFormat("Reached max-file-not-found count=%u", maxCount).str(),
  1140. downloadresultcode::MAX_FILE_NOT_FOUND);
  1141. }
  1142. }
  1143. void RequestGroup::markInMemoryDownload()
  1144. {
  1145. inMemoryDownload_ = true;
  1146. }
  1147. void RequestGroup::setTimeout(time_t timeout)
  1148. {
  1149. timeout_ = timeout;
  1150. }
  1151. bool RequestGroup::doesDownloadSpeedExceed()
  1152. {
  1153. return maxDownloadSpeedLimit_ > 0 &&
  1154. maxDownloadSpeedLimit_ < calculateStat().getDownloadSpeed();
  1155. }
  1156. bool RequestGroup::doesUploadSpeedExceed()
  1157. {
  1158. return maxUploadSpeedLimit_ > 0 &&
  1159. maxUploadSpeedLimit_ < calculateStat().getUploadSpeed();
  1160. }
  1161. void RequestGroup::setLastUriResult
  1162. (const std::string uri, downloadresultcode::RESULT result)
  1163. {
  1164. lastUriResult_.reset(new URIResult(uri, result));
  1165. }
  1166. void RequestGroup::saveControlFile() const
  1167. {
  1168. if(saveControlFile_) {
  1169. progressInfoFile_->save();
  1170. }
  1171. }
  1172. void RequestGroup::removeControlFile() const
  1173. {
  1174. progressInfoFile_->removeFile();
  1175. }
  1176. void RequestGroup::setDownloadContext
  1177. (const SharedHandle<DownloadContext>& downloadContext)
  1178. {
  1179. downloadContext_ = downloadContext;
  1180. if(!downloadContext_.isNull()) {
  1181. downloadContext_->setOwnerRequestGroup(this);
  1182. }
  1183. }
  1184. bool RequestGroup::p2pInvolved() const
  1185. {
  1186. #ifdef ENABLE_BITTORRENT
  1187. return downloadContext_->hasAttribute(bittorrent::BITTORRENT);
  1188. #else // !ENABLE_BITTORRENT
  1189. return false;
  1190. #endif // !ENABLE_BITTORRENT
  1191. }
  1192. gid_t RequestGroup::newGID()
  1193. {
  1194. if(gidCounter_ == INT64_MAX) {
  1195. gidCounter_ = 0;
  1196. }
  1197. return ++gidCounter_;
  1198. }
  1199. } // namespace aria2