RequestGroup.cc 41 KB

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