RequestGroup.cc 42 KB

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