RequestGroup.cc 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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 "PostDownloadHandler.h"
  37. #include "DownloadEngine.h"
  38. #include "DefaultSegmentManFactory.h"
  39. #include "SegmentMan.h"
  40. #include "NullProgressInfoFile.h"
  41. #include "Dependency.h"
  42. #include "prefs.h"
  43. #include "InitiateConnectionCommandFactory.h"
  44. #include "CUIDCounter.h"
  45. #include "File.h"
  46. #include "message.h"
  47. #include "Util.h"
  48. #include "BtRegistry.h"
  49. #include "LogFactory.h"
  50. #include "Logger.h"
  51. #include "DiskAdaptor.h"
  52. #include "DiskWriterFactory.h"
  53. #include "RecoverableException.h"
  54. #include "StreamCheckIntegrityEntry.h"
  55. #include "CheckIntegrityCommand.h"
  56. #include "UnknownLengthPieceStorage.h"
  57. #include "BtContext.h"
  58. #include "SingleFileDownloadContext.h"
  59. #include "DlAbortEx.h"
  60. #include "DownloadFailureException.h"
  61. #include "RequestGroupMan.h"
  62. #include "DefaultBtProgressInfoFile.h"
  63. #include "DefaultPieceStorage.h"
  64. #include "DownloadResult.h"
  65. #include "DownloadHandlerFactory.h"
  66. #include "MemoryBufferPreDownloadHandler.h"
  67. #include "DownloadHandlerConstants.h"
  68. #include "ServerHost.h"
  69. #include "Option.h"
  70. #include "FileEntry.h"
  71. #include "Request.h"
  72. #include "FileAllocationIterator.h"
  73. #include "StringFormat.h"
  74. #include "A2STR.h"
  75. #ifdef ENABLE_MESSAGE_DIGEST
  76. # include "CheckIntegrityCommand.h"
  77. #endif // ENABLE_MESSAGE_DIGEST
  78. #ifdef ENABLE_BITTORRENT
  79. # include "BtCheckIntegrityEntry.h"
  80. # include "DefaultPeerStorage.h"
  81. # include "DefaultBtAnnounce.h"
  82. # include "BtRuntime.h"
  83. # include "BtSetup.h"
  84. # include "BtFileAllocationEntry.h"
  85. # include "BtPostDownloadHandler.h"
  86. # include "DHTSetup.h"
  87. # include "DHTRegistry.h"
  88. # include "PeerObject.h"
  89. # include "BtMessageFactory.h"
  90. # include "BtRequestFactory.h"
  91. # include "BtMessageDispatcher.h"
  92. # include "BtMessageReceiver.h"
  93. # include "PeerConnection.h"
  94. # include "ExtensionMessageFactory.h"
  95. # include "DHTPeerAnnounceStorage.h"
  96. # include "DHTEntryPointNameResolveCommand.h"
  97. #endif // ENABLE_BITTORRENT
  98. #ifdef ENABLE_METALINK
  99. # include "MetalinkPostDownloadHandler.h"
  100. #endif // ENABLE_METALINK
  101. #include <cassert>
  102. #include <algorithm>
  103. namespace aria2 {
  104. int32_t RequestGroup::_gidCounter = 0;
  105. const std::string RequestGroup::ACCEPT_METALINK = "application/metalink+xml";
  106. RequestGroup::RequestGroup(const Option* option,
  107. const std::deque<std::string>& uris):
  108. _gid(++_gidCounter),
  109. _uris(uris),
  110. _numConcurrentCommand(0),
  111. _numStreamConnection(0),
  112. _numCommand(0),
  113. _segmentManFactory(new DefaultSegmentManFactory(option)),
  114. _progressInfoFile(new NullProgressInfoFile()),
  115. _preLocalFileCheckEnabled(true),
  116. _haltRequested(false),
  117. _forceHaltRequested(false),
  118. _singleHostMultiConnectionEnabled(true),
  119. _option(option),
  120. _logger(LogFactory::getInstance())
  121. {
  122. if(_option->get(PREF_FILE_ALLOCATION) == V_PREALLOC) {
  123. _fileAllocationEnabled = true;
  124. } else {
  125. _fileAllocationEnabled = false;
  126. }
  127. // Add types to be sent as a Accept header value here.
  128. // It would be good to put this value in Option so that user can tweak
  129. // and add this list.
  130. // ACCEPT_METALINK is used for `transparent metalink'.
  131. addAcceptType(ACCEPT_METALINK);
  132. initializePreDownloadHandler();
  133. initializePostDownloadHandler();
  134. }
  135. RequestGroup::~RequestGroup() {}
  136. SegmentManHandle RequestGroup::initSegmentMan()
  137. {
  138. _segmentMan = _segmentManFactory->createNewInstance(_downloadContext,
  139. _pieceStorage);
  140. return _segmentMan;
  141. }
  142. bool RequestGroup::downloadFinished() const
  143. {
  144. if(_pieceStorage.isNull()) {
  145. return false;
  146. } else {
  147. return _pieceStorage->downloadFinished();
  148. }
  149. }
  150. bool RequestGroup::allDownloadFinished() const
  151. {
  152. if(_pieceStorage.isNull()) {
  153. return false;
  154. } else {
  155. return _pieceStorage->allDownloadFinished();
  156. }
  157. }
  158. void RequestGroup::closeFile()
  159. {
  160. if(!_pieceStorage.isNull()) {
  161. _pieceStorage->getDiskAdaptor()->closeFile();
  162. }
  163. }
  164. void RequestGroup::createInitialCommand(std::deque<Command*>& commands,
  165. DownloadEngine* e)
  166. {
  167. #ifdef ENABLE_BITTORRENT
  168. {
  169. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  170. if(!btContext.isNull()) {
  171. if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
  172. throw DownloadFailureException
  173. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  174. getFilePath().c_str()).str());
  175. }
  176. initPieceStorage();
  177. if(btContext->getFileEntries().size() > 1) {
  178. // this is really multi file torrent.
  179. // clear http/ftp uris because the current implementation does not
  180. // allow integrating multi-file torrent and http/ftp.
  181. _logger->debug("Clearing http/ftp URIs because the current implementation does not allow integrating multi-file torrent and http/ftp.");
  182. _uris.clear();
  183. _pieceStorage->setFileFilter(Util::parseIntRange(_option->get(PREF_SELECT_FILE)));
  184. }
  185. BtProgressInfoFileHandle
  186. progressInfoFile(new DefaultBtProgressInfoFile(_downloadContext,
  187. _pieceStorage,
  188. _option));
  189. BtRegistry::registerBtContext(btContext->getInfoHashAsString(), btContext);
  190. BtRegistry::registerPieceStorage(btContext->getInfoHashAsString(),
  191. _pieceStorage);
  192. BtRegistry::registerBtProgressInfoFile(btContext->getInfoHashAsString(),
  193. progressInfoFile);
  194. BtRuntimeHandle btRuntime(new BtRuntime());
  195. btRuntime->setListenPort(_option->getAsInt(PREF_LISTEN_PORT));
  196. BtRegistry::registerBtRuntime(btContext->getInfoHashAsString(), btRuntime);
  197. PeerStorageHandle peerStorage(new DefaultPeerStorage(btContext, _option));
  198. BtRegistry::registerPeerStorage(btContext->getInfoHashAsString(), peerStorage);
  199. BtAnnounceHandle btAnnounce(new DefaultBtAnnounce(btContext, _option));
  200. BtRegistry::registerBtAnnounce(btContext->getInfoHashAsString(), btAnnounce);
  201. btAnnounce->shuffleAnnounce();
  202. {
  203. SharedHandle<PeerObjectCluster> po(new PeerObjectCluster());
  204. BtRegistry::registerPeerObjectCluster(btContext->getInfoHashAsString(),
  205. po);
  206. }
  207. // Remove the control file if download file doesn't exist
  208. if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) {
  209. progressInfoFile->removeFile();
  210. _logger->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  211. progressInfoFile->getFilename().c_str(),
  212. _pieceStorage->getDiskAdaptor()->getFilePath().c_str());
  213. }
  214. // Call Load, Save and file allocation command here
  215. if(progressInfoFile->exists()) {
  216. // load .aria2 file if it exists.
  217. progressInfoFile->load();
  218. _pieceStorage->getDiskAdaptor()->openFile();
  219. } else {
  220. if(_pieceStorage->getDiskAdaptor()->fileExists()) {
  221. if(!_option->getAsBool(PREF_CHECK_INTEGRITY) &&
  222. !_option->getAsBool(PREF_ALLOW_OVERWRITE) &&
  223. !_option->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  224. // TODO we need this->haltRequested = true?
  225. throw DownloadFailureException
  226. (StringFormat
  227. (MSG_FILE_ALREADY_EXISTS,
  228. _pieceStorage->getDiskAdaptor()->getFilePath().c_str()).str());
  229. } else {
  230. _pieceStorage->getDiskAdaptor()->openFile();
  231. }
  232. if(_option->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  233. _pieceStorage->markAllPiecesDone();
  234. }
  235. } else {
  236. _pieceStorage->getDiskAdaptor()->openFile();
  237. }
  238. }
  239. _progressInfoFile = progressInfoFile;
  240. if(!btContext->isPrivate() && _option->getAsBool(PREF_ENABLE_DHT)) {
  241. std::deque<Command*> commands;
  242. DHTSetup().setup(commands, e, _option);
  243. e->addCommand(commands);
  244. if(!btContext->getNodes().empty() && DHTSetup::initialized()) {
  245. DHTEntryPointNameResolveCommand* command =
  246. new DHTEntryPointNameResolveCommand(CUIDCounterSingletonHolder::instance()->newID(), e, btContext->getNodes());
  247. command->setTaskQueue(DHTRegistry::_taskQueue);
  248. command->setTaskFactory(DHTRegistry::_taskFactory);
  249. command->setRoutingTable(DHTRegistry::_routingTable);
  250. command->setLocalNode(DHTRegistry::_localNode);
  251. e->commands.push_back(command);
  252. }
  253. }
  254. CheckIntegrityEntryHandle entry(new BtCheckIntegrityEntry(this));
  255. // --bt-seed-unverified=true is given and download has completed, skip
  256. // validation for piece hashes.
  257. if(_option->getAsBool(PREF_BT_SEED_UNVERIFIED) &&
  258. _pieceStorage->downloadFinished()) {
  259. entry->onDownloadFinished(commands, e);
  260. } else {
  261. processCheckIntegrityEntry(commands, entry, e);
  262. }
  263. return;
  264. }
  265. }
  266. #endif // ENABLE_BITTORRENT
  267. // TODO I assume here when totallength is set to DownloadContext and it is
  268. // not 0, then filepath is also set DownloadContext correctly....
  269. if(_downloadContext->getTotalLength() == 0) {
  270. createNextCommand(commands, e, 1);
  271. }else {
  272. if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
  273. throw DownloadFailureException
  274. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  275. getFilePath().c_str()).str());
  276. }
  277. initPieceStorage();
  278. BtProgressInfoFileHandle infoFile
  279. (new DefaultBtProgressInfoFile(_downloadContext, _pieceStorage, _option));
  280. if(infoFile->exists() || !downloadFinishedByFileLength()) {
  281. loadAndOpenFile(infoFile);
  282. SharedHandle<CheckIntegrityEntry> checkIntegrityEntry
  283. (new StreamCheckIntegrityEntry(SharedHandle<Request>(), this));
  284. processCheckIntegrityEntry(commands, checkIntegrityEntry, e);
  285. }
  286. }
  287. }
  288. void RequestGroup::processCheckIntegrityEntry(std::deque<Command*>& commands,
  289. const CheckIntegrityEntryHandle& entry,
  290. DownloadEngine* e)
  291. {
  292. #ifdef ENABLE_MESSAGE_DIGEST
  293. if(e->option->getAsBool(PREF_CHECK_INTEGRITY) &&
  294. entry->isValidationReady()) {
  295. entry->initValidator();
  296. CheckIntegrityCommand* command =
  297. new CheckIntegrityCommand(CUIDCounterSingletonHolder::instance()->newID(), this, e, entry);
  298. commands.push_back(command);
  299. } else
  300. #endif // ENABLE_MESSAGE_DIGEST
  301. {
  302. entry->onDownloadIncomplete(commands, e);
  303. }
  304. }
  305. void RequestGroup::initPieceStorage()
  306. {
  307. if(_downloadContext->getTotalLength() == 0) {
  308. UnknownLengthPieceStorageHandle ps(new UnknownLengthPieceStorage(_downloadContext, _option));
  309. if(!_diskWriterFactory.isNull()) {
  310. ps->setDiskWriterFactory(_diskWriterFactory);
  311. }
  312. _pieceStorage = ps;
  313. } else {
  314. DefaultPieceStorageHandle ps(new DefaultPieceStorage(_downloadContext, _option));
  315. if(!_diskWriterFactory.isNull()) {
  316. ps->setDiskWriterFactory(_diskWriterFactory);
  317. }
  318. _pieceStorage = ps;
  319. }
  320. _pieceStorage->initStorage();
  321. initSegmentMan();
  322. }
  323. bool RequestGroup::downloadFinishedByFileLength()
  324. {
  325. // assuming that a control file doesn't exist.
  326. if(!isPreLocalFileCheckEnabled() ||
  327. _option->getAsBool(PREF_ALLOW_OVERWRITE) ||
  328. (_option->getAsBool(PREF_CHECK_INTEGRITY) &&
  329. !_downloadContext->getPieceHashes().empty())) {
  330. return false;
  331. }
  332. // TODO consider the case when the getFilePath() returns dir path.
  333. File outfile(getFilePath());
  334. if(outfile.exists() && getTotalLength() == outfile.size()) {
  335. _pieceStorage->markAllPiecesDone();
  336. _logger->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, _gid, getFilePath().c_str());
  337. return true;
  338. } else {
  339. return false;
  340. }
  341. }
  342. void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoFile)
  343. {
  344. try {
  345. if(!isPreLocalFileCheckEnabled()) {
  346. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  347. return;
  348. }
  349. // Remove the control file if download file doesn't exist
  350. if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) {
  351. progressInfoFile->removeFile();
  352. _logger->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  353. progressInfoFile->getFilename().c_str(),
  354. _pieceStorage->getDiskAdaptor()->getFilePath().c_str());
  355. }
  356. while(1) {
  357. if(progressInfoFile->exists()) {
  358. progressInfoFile->load();
  359. _pieceStorage->getDiskAdaptor()->openExistingFile();
  360. } else {
  361. File outfile(getFilePath());
  362. if(outfile.exists() && _option->getAsBool(PREF_CONTINUE)) {
  363. if(getTotalLength() < outfile.size()) {
  364. throw DlAbortEx
  365. (StringFormat(EX_FILE_LENGTH_MISMATCH_BETWEEN_LOCAL_AND_REMOTE,
  366. getFilePath().c_str(),
  367. Util::itos(outfile.size()).c_str(),
  368. Util::itos(getTotalLength()).c_str()).str());
  369. }
  370. _pieceStorage->getDiskAdaptor()->openExistingFile();
  371. _pieceStorage->markPiecesDone(outfile.size());
  372. } else {
  373. #ifdef ENABLE_MESSAGE_DIGEST
  374. if(outfile.exists() && _option->getAsBool(PREF_CHECK_INTEGRITY)) {
  375. _pieceStorage->getDiskAdaptor()->openExistingFile();
  376. } else {
  377. #endif // ENABLE_MESSAGE_DIGEST
  378. shouldCancelDownloadForSafety();
  379. // call updateFilename here in case when filename is renamed
  380. // by tryAutoFileRenaming()
  381. progressInfoFile->updateFilename();
  382. if(progressInfoFile->exists()) {
  383. // Close DiskAdaptor here. Renmaed file will be opened in the
  384. // next loop .
  385. _pieceStorage->getDiskAdaptor()->closeFile();
  386. continue;
  387. }
  388. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  389. #ifdef ENABLE_MESSAGE_DIGEST
  390. }
  391. #endif // ENABLE_MESSAGE_DIGEST
  392. }
  393. }
  394. setProgressInfoFile(progressInfoFile);
  395. break;
  396. }
  397. } catch(RecoverableException& e) {
  398. throw DownloadFailureException
  399. (StringFormat(EX_DOWNLOAD_ABORTED).str(), e);
  400. }
  401. }
  402. // assuming that a control file does not exist
  403. void RequestGroup::shouldCancelDownloadForSafety()
  404. {
  405. if(_option->getAsBool(PREF_ALLOW_OVERWRITE)) {
  406. return;
  407. }
  408. File outfile(getFilePath());
  409. if(outfile.exists()) {
  410. if(_option->getAsBool(PREF_AUTO_FILE_RENAMING)) {
  411. if(tryAutoFileRenaming()) {
  412. _logger->notice(MSG_FILE_RENAMED, getFilePath().c_str());
  413. } else {
  414. throw DownloadFailureException
  415. (StringFormat("File renaming failed: %s",
  416. getFilePath().c_str()).str());
  417. }
  418. } else {
  419. throw DownloadFailureException
  420. (StringFormat(MSG_FILE_ALREADY_EXISTS,
  421. getFilePath().c_str()).str());
  422. }
  423. }
  424. }
  425. bool RequestGroup::tryAutoFileRenaming()
  426. {
  427. std::string filepath = getFilePath();
  428. if(filepath.empty()) {
  429. return false;
  430. }
  431. SingleFileDownloadContextHandle ctx =
  432. dynamic_pointer_cast<SingleFileDownloadContext>(_downloadContext);
  433. // Make a copy of ctx.
  434. SingleFileDownloadContextHandle tempCtx(new SingleFileDownloadContext(*ctx.get()));
  435. DefaultBtProgressInfoFile tempInfoFile(tempCtx, SharedHandle<PieceStorage>(), 0);
  436. for(unsigned int i = 1; i < 10000; ++i) {
  437. File newfile(filepath+"."+Util::uitos(i));
  438. std::string newFilename = newfile.getBasename();
  439. tempCtx->setUFilename(newFilename);
  440. tempInfoFile.updateFilename();
  441. if(!newfile.exists() || (newfile.exists() && tempInfoFile.exists())) {
  442. ctx->setUFilename(newFilename);
  443. return true;
  444. }
  445. }
  446. return false;
  447. }
  448. void RequestGroup::createNextCommandWithAdj(std::deque<Command*>& commands,
  449. DownloadEngine* e, int numAdj)
  450. {
  451. unsigned int numCommand;
  452. if(_numConcurrentCommand == 0) {
  453. numCommand = _uris.size();
  454. } else {
  455. int n = _numConcurrentCommand+numAdj;
  456. if(n > 0) {
  457. numCommand = n;
  458. } else {
  459. return;
  460. }
  461. }
  462. createNextCommand(commands, e, numCommand, Request::METHOD_GET);
  463. }
  464. void RequestGroup::createNextCommand(std::deque<Command*>& commands,
  465. DownloadEngine* e,
  466. unsigned int numCommand,
  467. const std::string& method)
  468. {
  469. std::deque<std::string> pendingURIs;
  470. for(;!_uris.empty() && numCommand--; _uris.pop_front()) {
  471. std::string uri = _uris.front();
  472. RequestHandle req(new Request());
  473. if(req->setUrl(uri)) {
  474. ServerHostHandle sv;
  475. if(!_singleHostMultiConnectionEnabled){
  476. sv = searchServerHost(req->getHost());
  477. }
  478. if(sv.isNull()) {
  479. _spentUris.push_back(uri);
  480. req->setReferer(_option->get(PREF_REFERER));
  481. req->setMethod(method);
  482. Command* command = InitiateConnectionCommandFactory::createInitiateConnectionCommand(CUIDCounterSingletonHolder::instance()->newID(), req, this, e);
  483. ServerHostHandle sv(new ServerHost(command->getCuid(), req->getHost()));
  484. registerServerHost(sv);
  485. // give a chance to be executed in the next loop in DownloadEngine
  486. command->setStatus(Command::STATUS_ONESHOT_REALTIME);
  487. commands.push_back(command);
  488. } else {
  489. pendingURIs.push_back(uri);
  490. }
  491. } else {
  492. _logger->error(MSG_UNRECOGNIZED_URI, req->getUrl().c_str());
  493. }
  494. }
  495. _uris.insert(_uris.begin(), pendingURIs.begin(), pendingURIs.end());
  496. }
  497. std::string RequestGroup::getFilePath() const
  498. {
  499. assert(!_downloadContext.isNull());
  500. if(_downloadContext.isNull()) {
  501. return A2STR::NIL;
  502. } else {
  503. return _downloadContext->getActualBasePath();
  504. }
  505. }
  506. uint64_t RequestGroup::getTotalLength() const
  507. {
  508. if(_pieceStorage.isNull()) {
  509. return 0;
  510. } else {
  511. if(_pieceStorage->isSelectiveDownloadingMode()) {
  512. return _pieceStorage->getFilteredTotalLength();
  513. } else {
  514. return _pieceStorage->getTotalLength();
  515. }
  516. }
  517. }
  518. uint64_t RequestGroup::getCompletedLength() const
  519. {
  520. if(_pieceStorage.isNull()) {
  521. return 0;
  522. } else {
  523. if(_pieceStorage->isSelectiveDownloadingMode()) {
  524. return _pieceStorage->getFilteredCompletedLength();
  525. } else {
  526. return _pieceStorage->getCompletedLength();
  527. }
  528. }
  529. }
  530. void RequestGroup::validateFilename(const std::string& expectedFilename,
  531. const std::string& actualFilename) const
  532. {
  533. if(expectedFilename.empty()) {
  534. return;
  535. }
  536. if(expectedFilename != actualFilename) {
  537. throw DlAbortEx(StringFormat(EX_FILENAME_MISMATCH,
  538. expectedFilename.c_str(),
  539. actualFilename.c_str()).str());
  540. }
  541. }
  542. void RequestGroup::validateTotalLength(uint64_t expectedTotalLength,
  543. uint64_t actualTotalLength) const
  544. {
  545. if(expectedTotalLength <= 0) {
  546. return;
  547. }
  548. if(expectedTotalLength != actualTotalLength) {
  549. throw DlAbortEx
  550. (StringFormat(EX_SIZE_MISMATCH,
  551. Util::itos(expectedTotalLength, true).c_str(),
  552. Util::itos(actualTotalLength, true).c_str()).str());
  553. }
  554. }
  555. void RequestGroup::validateFilename(const std::string& actualFilename) const
  556. {
  557. validateFilename(_downloadContext->getFileEntries().front()->getBasename(), actualFilename);
  558. }
  559. void RequestGroup::validateTotalLength(uint64_t actualTotalLength) const
  560. {
  561. validateTotalLength(getTotalLength(), actualTotalLength);
  562. }
  563. void RequestGroup::increaseStreamConnection()
  564. {
  565. ++_numStreamConnection;
  566. }
  567. void RequestGroup::decreaseStreamConnection()
  568. {
  569. --_numStreamConnection;
  570. }
  571. unsigned int RequestGroup::getNumConnection() const
  572. {
  573. unsigned int numConnection = _numStreamConnection;
  574. #ifdef ENABLE_BITTORRENT
  575. {
  576. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  577. if(!btContext.isNull()) {
  578. BtRuntimeHandle btRuntime = BT_RUNTIME(btContext);
  579. if(!btRuntime.isNull()) {
  580. numConnection += btRuntime->getConnections();
  581. }
  582. }
  583. }
  584. #endif // ENABLE_BITTORRENT
  585. return numConnection;
  586. }
  587. void RequestGroup::increaseNumCommand()
  588. {
  589. ++_numCommand;
  590. }
  591. void RequestGroup::decreaseNumCommand()
  592. {
  593. --_numCommand;
  594. }
  595. TransferStat RequestGroup::calculateStat()
  596. {
  597. TransferStat stat;
  598. #ifdef ENABLE_BITTORRENT
  599. {
  600. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  601. if(!btContext.isNull()) {
  602. PeerStorageHandle peerStorage = PEER_STORAGE(btContext);
  603. if(!peerStorage.isNull()) {
  604. stat = peerStorage->calculateStat();
  605. }
  606. }
  607. }
  608. #endif // ENABLE_BITTORRENT
  609. if(!_segmentMan.isNull()) {
  610. stat.setDownloadSpeed(stat.getDownloadSpeed()+_segmentMan->calculateDownloadSpeed());
  611. }
  612. return stat;
  613. }
  614. void RequestGroup::setHaltRequested(bool f)
  615. {
  616. _haltRequested = f;
  617. #ifdef ENABLE_BITTORRENT
  618. {
  619. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  620. if(!btContext.isNull()) {
  621. BtRuntimeHandle btRuntime = BT_RUNTIME(btContext);
  622. if(!btRuntime.isNull()) {
  623. btRuntime->setHalt(f);
  624. }
  625. }
  626. }
  627. #endif // ENABLE_BITTORRENT
  628. }
  629. void RequestGroup::setForceHaltRequested(bool f)
  630. {
  631. setHaltRequested(f);
  632. _forceHaltRequested = f;
  633. }
  634. void RequestGroup::releaseRuntimeResource()
  635. {
  636. #ifdef ENABLE_BITTORRENT
  637. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  638. if(!btContext.isNull()) {
  639. BtContextHandle btContextInReg = BtRegistry::getBtContext(btContext->getInfoHashAsString());
  640. if(!btContextInReg.isNull() &&
  641. btContextInReg->getOwnerRequestGroup()->getGID() ==
  642. btContext->getOwnerRequestGroup()->getGID()) {
  643. BtRegistry::unregister(btContext->getInfoHashAsString());
  644. if(!DHTRegistry::_peerAnnounceStorage.isNull()) {
  645. DHTRegistry::_peerAnnounceStorage->removePeerAnnounce(btContext);
  646. }
  647. }
  648. }
  649. #endif // ENABLE_BITTORRENT
  650. if(!_pieceStorage.isNull()) {
  651. _pieceStorage->removeAdvertisedPiece(0);
  652. }
  653. }
  654. void RequestGroup::preDownloadProcessing()
  655. {
  656. _logger->debug("Finding PreDownloadHandler for path %s.", getFilePath().c_str());
  657. try {
  658. for(PreDownloadHandlers::const_iterator itr = _preDownloadHandlers.begin();
  659. itr != _preDownloadHandlers.end(); ++itr) {
  660. if((*itr)->canHandle(this)) {
  661. (*itr)->execute(this);
  662. return;
  663. }
  664. }
  665. } catch(RecoverableException& ex) {
  666. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  667. return;
  668. }
  669. _logger->debug("No PreDownloadHandler found.");
  670. return;
  671. }
  672. void RequestGroup::postDownloadProcessing
  673. (std::deque<SharedHandle<RequestGroup> >& groups)
  674. {
  675. _logger->debug("Finding PostDownloadHandler for path %s.", getFilePath().c_str());
  676. try {
  677. for(PostDownloadHandlers::const_iterator itr = _postDownloadHandlers.begin();
  678. itr != _postDownloadHandlers.end(); ++itr) {
  679. if((*itr)->canHandle(this)) {
  680. (*itr)->getNextRequestGroups(groups, this);
  681. return;
  682. }
  683. }
  684. } catch(RecoverableException& ex) {
  685. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  686. }
  687. _logger->debug("No PostDownloadHandler found.");
  688. }
  689. void RequestGroup::initializePreDownloadHandler()
  690. {
  691. #ifdef ENABLE_BITTORRENT
  692. if(_option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  693. _preDownloadHandlers.push_back(DownloadHandlerFactory::getBtPreDownloadHandler());
  694. }
  695. #endif // ENABLE_BITTORRENT
  696. #ifdef ENABLE_METALINK
  697. if(_option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  698. _preDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPreDownloadHandler());
  699. }
  700. #endif // ENABLE_METALINK
  701. }
  702. void RequestGroup::initializePostDownloadHandler()
  703. {
  704. #ifdef ENABLE_BITTORRENT
  705. if(_option->getAsBool(PREF_FOLLOW_TORRENT) ||
  706. _option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  707. _postDownloadHandlers.push_back(DownloadHandlerFactory::getBtPostDownloadHandler());
  708. }
  709. #endif // ENABLE_BITTORRENT
  710. #ifdef ENABLE_METALINK
  711. if(_option->getAsBool(PREF_FOLLOW_METALINK) ||
  712. _option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  713. _postDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPostDownloadHandler());
  714. }
  715. #endif // ENABLE_METALINK
  716. }
  717. void RequestGroup::getURIs(std::deque<std::string>& uris) const
  718. {
  719. uris.insert(uris.end(), _spentUris.begin(), _spentUris.end());
  720. uris.insert(uris.end(), _uris.begin(), _uris.end());
  721. }
  722. bool RequestGroup::isDependencyResolved()
  723. {
  724. if(_dependency.isNull()) {
  725. return true;
  726. }
  727. return _dependency->resolve();
  728. }
  729. void RequestGroup::setSegmentManFactory(const SegmentManFactoryHandle& segmentManFactory)
  730. {
  731. _segmentManFactory = segmentManFactory;
  732. }
  733. void RequestGroup::dependsOn(const DependencyHandle& dep)
  734. {
  735. _dependency = dep;
  736. }
  737. void RequestGroup::setDiskWriterFactory(const DiskWriterFactoryHandle& diskWriterFactory)
  738. {
  739. _diskWriterFactory = diskWriterFactory;
  740. }
  741. DiskWriterFactoryHandle RequestGroup::getDiskWriterFactory() const
  742. {
  743. return _diskWriterFactory;
  744. }
  745. void RequestGroup::addPostDownloadHandler(const PostDownloadHandlerHandle& handler)
  746. {
  747. _postDownloadHandlers.push_back(handler);
  748. }
  749. void RequestGroup::addPreDownloadHandler(const PreDownloadHandlerHandle& handler)
  750. {
  751. _preDownloadHandlers.push_back(handler);
  752. }
  753. void RequestGroup::clearPostDowloadHandler()
  754. {
  755. _postDownloadHandlers.clear();
  756. }
  757. void RequestGroup::clearPreDowloadHandler()
  758. {
  759. _preDownloadHandlers.clear();
  760. }
  761. SegmentManHandle RequestGroup::getSegmentMan() const
  762. {
  763. return _segmentMan;
  764. }
  765. DownloadContextHandle RequestGroup::getDownloadContext() const
  766. {
  767. return _downloadContext;
  768. }
  769. void RequestGroup::setDownloadContext(const DownloadContextHandle& downloadContext)
  770. {
  771. _downloadContext = downloadContext;
  772. }
  773. PieceStorageHandle RequestGroup::getPieceStorage() const
  774. {
  775. return _pieceStorage;
  776. }
  777. void RequestGroup::setPieceStorage(const PieceStorageHandle& pieceStorage)
  778. {
  779. _pieceStorage = pieceStorage;
  780. }
  781. BtProgressInfoFileHandle RequestGroup::getProgressInfoFile() const
  782. {
  783. return _progressInfoFile;
  784. }
  785. void RequestGroup::setProgressInfoFile(const BtProgressInfoFileHandle& progressInfoFile)
  786. {
  787. _progressInfoFile = progressInfoFile;
  788. }
  789. bool RequestGroup::needsFileAllocation() const
  790. {
  791. return isFileAllocationEnabled() &&
  792. (uint64_t)_option->getAsLLInt(PREF_NO_FILE_ALLOCATION_LIMIT) <= getTotalLength() &&
  793. !_pieceStorage->getDiskAdaptor()->fileAllocationIterator()->finished();
  794. }
  795. DownloadResultHandle RequestGroup::createDownloadResult() const
  796. {
  797. std::deque<std::string> uris;
  798. getURIs(uris);
  799. return
  800. SharedHandle<DownloadResult>(new DownloadResult(_gid,
  801. getFilePath(),
  802. getTotalLength(),
  803. uris.empty() ? A2STR::NIL:uris.front(),
  804. uris.size(),
  805. downloadFinished()?
  806. DownloadResult::FINISHED :
  807. DownloadResult::NOT_YET));
  808. }
  809. void RequestGroup::registerServerHost(const ServerHostHandle& serverHost)
  810. {
  811. _serverHosts.push_back(serverHost);
  812. }
  813. class FindServerHostByCUID
  814. {
  815. private:
  816. int32_t _cuid;
  817. public:
  818. FindServerHostByCUID(int32_t cuid):_cuid(cuid) {}
  819. bool operator()(const ServerHostHandle& sv) const
  820. {
  821. return sv->getCuid() == _cuid;
  822. }
  823. };
  824. ServerHostHandle RequestGroup::searchServerHost(int32_t cuid) const
  825. {
  826. std::deque<SharedHandle<ServerHost> >::const_iterator itr =
  827. std::find_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByCUID(cuid));
  828. if(itr == _serverHosts.end()) {
  829. return SharedHandle<ServerHost>();
  830. } else {
  831. return *itr;
  832. }
  833. }
  834. class FindServerHostByHostname
  835. {
  836. private:
  837. std::string _hostname;
  838. public:
  839. FindServerHostByHostname(const std::string& hostname):_hostname(hostname) {}
  840. bool operator()(const ServerHostHandle& sv) const
  841. {
  842. return sv->getHostname() == _hostname;
  843. }
  844. };
  845. ServerHostHandle RequestGroup::searchServerHost(const std::string& hostname) const
  846. {
  847. std::deque<SharedHandle<ServerHost> >::const_iterator itr =
  848. std::find_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByHostname(hostname));
  849. if(itr == _serverHosts.end()) {
  850. return SharedHandle<ServerHost>();
  851. } else {
  852. return *itr;
  853. }
  854. }
  855. void RequestGroup::removeServerHost(int32_t cuid)
  856. {
  857. _serverHosts.erase(std::remove_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByCUID(cuid)), _serverHosts.end());
  858. }
  859. void RequestGroup::removeURIWhoseHostnameIs(const std::string& hostname)
  860. {
  861. std::deque<std::string> newURIs;
  862. Request req;
  863. for(std::deque<std::string>::const_iterator itr = _uris.begin(); itr != _uris.end(); ++itr) {
  864. if(((*itr).find(hostname) == std::string::npos) ||
  865. (req.setUrl(*itr) && (req.getHost() != hostname))) {
  866. newURIs.push_back(*itr);
  867. }
  868. }
  869. _logger->debug("GUID#%d - Removed %d duplicate hostname URIs",
  870. _gid, _uris.size()-newURIs.size());
  871. _uris = newURIs;
  872. }
  873. void RequestGroup::reportDownloadFinished()
  874. {
  875. _logger->notice(MSG_FILE_DOWNLOAD_COMPLETED,
  876. getFilePath().c_str());
  877. #ifdef ENABLE_BITTORRENT
  878. TransferStat stat = calculateStat();
  879. SharedHandle<BtContext> ctx = dynamic_pointer_cast<BtContext>(_downloadContext);
  880. if(!ctx.isNull()) {
  881. double shareRatio = ((stat.getAllTimeUploadLength()*10)/getCompletedLength())/10.0;
  882. _logger->notice(MSG_SHARE_RATIO_REPORT,
  883. shareRatio,
  884. Util::abbrevSize(stat.getAllTimeUploadLength()).c_str(),
  885. Util::abbrevSize(getCompletedLength()).c_str());
  886. }
  887. #endif // ENABLE_BITTORRENT
  888. }
  889. const std::deque<std::string>& RequestGroup::getAcceptFeatures() const
  890. {
  891. return _acceptFeatures;
  892. }
  893. void RequestGroup::addAcceptFeatureHeader(const std::string& feature)
  894. {
  895. if(std::find(_acceptFeatures.begin(), _acceptFeatures.end(), feature) == _acceptFeatures.end()) {
  896. _acceptFeatures.push_back(feature);
  897. }
  898. }
  899. void RequestGroup::removeAcceptFeatureHeader(const std::string& feature)
  900. {
  901. std::deque<std::string>::iterator i = std::find(_acceptFeatures.begin(), _acceptFeatures.end(), feature);
  902. if(i != _acceptFeatures.end()) {
  903. _acceptFeatures.erase(i);
  904. }
  905. }
  906. const std::deque<std::string>& RequestGroup::getAcceptTypes() const
  907. {
  908. return _acceptTypes;
  909. }
  910. void RequestGroup::addAcceptType(const std::string& type)
  911. {
  912. if(std::find(_acceptTypes.begin(), _acceptTypes.end(), type) == _acceptTypes.end()) {
  913. _acceptTypes.push_back(type);
  914. }
  915. }
  916. void RequestGroup::removeAcceptType(const std::string& type)
  917. {
  918. _acceptTypes.erase(std::remove(_acceptTypes.begin(), _acceptTypes.end(), type),
  919. _acceptTypes.end());
  920. }
  921. } // namespace aria2