RequestGroup.cc 30 KB

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