RequestGroup.cc 42 KB

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