RequestGroup.cc 42 KB

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