RequestGroup.cc 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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. entry->cutTrailingGarbage();
  300. CheckIntegrityCommand* command =
  301. new CheckIntegrityCommand(CUIDCounterSingletonHolder::instance()->newID(), this, e, entry);
  302. commands.push_back(command);
  303. } else
  304. #endif // ENABLE_MESSAGE_DIGEST
  305. {
  306. entry->onDownloadIncomplete(commands, e);
  307. }
  308. }
  309. void RequestGroup::initPieceStorage()
  310. {
  311. if(_downloadContext->getTotalLength() == 0) {
  312. UnknownLengthPieceStorageHandle ps(new UnknownLengthPieceStorage(_downloadContext, _option));
  313. if(!_diskWriterFactory.isNull()) {
  314. ps->setDiskWriterFactory(_diskWriterFactory);
  315. }
  316. _pieceStorage = ps;
  317. } else {
  318. DefaultPieceStorageHandle ps(new DefaultPieceStorage(_downloadContext, _option));
  319. if(!_diskWriterFactory.isNull()) {
  320. ps->setDiskWriterFactory(_diskWriterFactory);
  321. }
  322. _pieceStorage = ps;
  323. }
  324. _pieceStorage->initStorage();
  325. initSegmentMan();
  326. }
  327. bool RequestGroup::downloadFinishedByFileLength()
  328. {
  329. // assuming that a control file doesn't exist.
  330. if(!isPreLocalFileCheckEnabled() ||
  331. _option->getAsBool(PREF_ALLOW_OVERWRITE) ||
  332. (_option->getAsBool(PREF_CHECK_INTEGRITY) &&
  333. !_downloadContext->getPieceHashes().empty())) {
  334. return false;
  335. }
  336. // TODO consider the case when the getFilePath() returns dir path.
  337. File outfile(getFilePath());
  338. if(outfile.exists() && getTotalLength() == outfile.size()) {
  339. _pieceStorage->markAllPiecesDone();
  340. _logger->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, _gid, getFilePath().c_str());
  341. return true;
  342. } else {
  343. return false;
  344. }
  345. }
  346. void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoFile)
  347. {
  348. try {
  349. if(!isPreLocalFileCheckEnabled()) {
  350. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  351. return;
  352. }
  353. // Remove the control file if download file doesn't exist
  354. if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) {
  355. progressInfoFile->removeFile();
  356. _logger->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  357. progressInfoFile->getFilename().c_str(),
  358. _pieceStorage->getDiskAdaptor()->getFilePath().c_str());
  359. }
  360. while(1) {
  361. if(progressInfoFile->exists()) {
  362. progressInfoFile->load();
  363. _pieceStorage->getDiskAdaptor()->openExistingFile();
  364. } else {
  365. File outfile(getFilePath());
  366. if(outfile.exists() && _option->getAsBool(PREF_CONTINUE)) {
  367. if(getTotalLength() < outfile.size()) {
  368. throw DlAbortEx
  369. (StringFormat(EX_FILE_LENGTH_MISMATCH_BETWEEN_LOCAL_AND_REMOTE,
  370. getFilePath().c_str(),
  371. Util::itos(outfile.size()).c_str(),
  372. Util::itos(getTotalLength()).c_str()).str());
  373. }
  374. _pieceStorage->getDiskAdaptor()->openExistingFile();
  375. _pieceStorage->markPiecesDone(outfile.size());
  376. } else {
  377. #ifdef ENABLE_MESSAGE_DIGEST
  378. if(outfile.exists() && _option->getAsBool(PREF_CHECK_INTEGRITY)) {
  379. _pieceStorage->getDiskAdaptor()->openExistingFile();
  380. } else {
  381. #endif // ENABLE_MESSAGE_DIGEST
  382. shouldCancelDownloadForSafety();
  383. // call updateFilename here in case when filename is renamed
  384. // by tryAutoFileRenaming()
  385. progressInfoFile->updateFilename();
  386. if(progressInfoFile->exists()) {
  387. // Close DiskAdaptor here. Renmaed file will be opened in the
  388. // next loop .
  389. _pieceStorage->getDiskAdaptor()->closeFile();
  390. continue;
  391. }
  392. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  393. #ifdef ENABLE_MESSAGE_DIGEST
  394. }
  395. #endif // ENABLE_MESSAGE_DIGEST
  396. }
  397. }
  398. setProgressInfoFile(progressInfoFile);
  399. break;
  400. }
  401. } catch(RecoverableException& e) {
  402. throw DownloadFailureException
  403. (StringFormat(EX_DOWNLOAD_ABORTED).str(), e);
  404. }
  405. }
  406. // assuming that a control file does not exist
  407. void RequestGroup::shouldCancelDownloadForSafety()
  408. {
  409. if(_option->getAsBool(PREF_ALLOW_OVERWRITE)) {
  410. return;
  411. }
  412. File outfile(getFilePath());
  413. if(outfile.exists()) {
  414. if(_option->getAsBool(PREF_AUTO_FILE_RENAMING)) {
  415. if(tryAutoFileRenaming()) {
  416. _logger->notice(MSG_FILE_RENAMED, getFilePath().c_str());
  417. } else {
  418. throw DownloadFailureException
  419. (StringFormat("File renaming failed: %s",
  420. getFilePath().c_str()).str());
  421. }
  422. } else {
  423. throw DownloadFailureException
  424. (StringFormat(MSG_FILE_ALREADY_EXISTS,
  425. getFilePath().c_str()).str());
  426. }
  427. }
  428. }
  429. bool RequestGroup::tryAutoFileRenaming()
  430. {
  431. std::string filepath = getFilePath();
  432. if(filepath.empty()) {
  433. return false;
  434. }
  435. SingleFileDownloadContextHandle ctx =
  436. dynamic_pointer_cast<SingleFileDownloadContext>(_downloadContext);
  437. // Make a copy of ctx.
  438. SingleFileDownloadContextHandle tempCtx(new SingleFileDownloadContext(*ctx.get()));
  439. DefaultBtProgressInfoFile tempInfoFile(tempCtx, SharedHandle<PieceStorage>(), 0);
  440. for(unsigned int i = 1; i < 10000; ++i) {
  441. File newfile(filepath+"."+Util::uitos(i));
  442. std::string newFilename = newfile.getBasename();
  443. tempCtx->setUFilename(newFilename);
  444. tempInfoFile.updateFilename();
  445. if(!newfile.exists() || (newfile.exists() && tempInfoFile.exists())) {
  446. ctx->setUFilename(newFilename);
  447. return true;
  448. }
  449. }
  450. return false;
  451. }
  452. void RequestGroup::createNextCommandWithAdj(std::deque<Command*>& commands,
  453. DownloadEngine* e, int numAdj)
  454. {
  455. int numCommand;
  456. if(getTotalLength() == 0) {
  457. numCommand = 1+numAdj;
  458. } else {
  459. if(_numConcurrentCommand == 0) {
  460. numCommand = _uris.size();
  461. } else {
  462. numCommand = _numConcurrentCommand;
  463. }
  464. numCommand = std::min(static_cast<int>(_downloadContext->getNumPieces()),
  465. numCommand);
  466. numCommand += numAdj;
  467. }
  468. if(numCommand > 0) {
  469. createNextCommand(commands, e, numCommand);
  470. }
  471. }
  472. void RequestGroup::createNextCommand(std::deque<Command*>& commands,
  473. DownloadEngine* e,
  474. unsigned int numCommand,
  475. const std::string& method)
  476. {
  477. std::deque<std::string> pendingURIs;
  478. for(; !_uris.empty() && numCommand--; ) {
  479. std::string uri = _uriSelector->select(_uris);
  480. RequestHandle req(new Request());
  481. if(req->setUrl(uri)) {
  482. ServerHostHandle sv;
  483. if(!_singleHostMultiConnectionEnabled){
  484. sv = searchServerHost(req->getHost());
  485. }
  486. if(sv.isNull()) {
  487. _spentUris.push_back(uri);
  488. req->setReferer(_option->get(PREF_REFERER));
  489. req->setMethod(method);
  490. Command* command = InitiateConnectionCommandFactory::createInitiateConnectionCommand(CUIDCounterSingletonHolder::instance()->newID(), req, this, e);
  491. ServerHostHandle sv(new ServerHost(command->getCuid(), req->getHost()));
  492. registerServerHost(sv);
  493. // give a chance to be executed in the next loop in DownloadEngine
  494. command->setStatus(Command::STATUS_ONESHOT_REALTIME);
  495. commands.push_back(command);
  496. } else {
  497. pendingURIs.push_back(uri);
  498. }
  499. } else {
  500. _logger->error(MSG_UNRECOGNIZED_URI, req->getUrl().c_str());
  501. }
  502. }
  503. _uris.insert(_uris.begin(), pendingURIs.begin(), pendingURIs.end());
  504. }
  505. std::string RequestGroup::getFilePath() const
  506. {
  507. assert(!_downloadContext.isNull());
  508. if(_downloadContext.isNull()) {
  509. return A2STR::NIL;
  510. } else {
  511. return _downloadContext->getActualBasePath();
  512. }
  513. }
  514. uint64_t RequestGroup::getTotalLength() const
  515. {
  516. if(_pieceStorage.isNull()) {
  517. return 0;
  518. } else {
  519. if(_pieceStorage->isSelectiveDownloadingMode()) {
  520. return _pieceStorage->getFilteredTotalLength();
  521. } else {
  522. return _pieceStorage->getTotalLength();
  523. }
  524. }
  525. }
  526. uint64_t RequestGroup::getCompletedLength() const
  527. {
  528. if(_pieceStorage.isNull()) {
  529. return 0;
  530. } else {
  531. if(_pieceStorage->isSelectiveDownloadingMode()) {
  532. return _pieceStorage->getFilteredCompletedLength();
  533. } else {
  534. return _pieceStorage->getCompletedLength();
  535. }
  536. }
  537. }
  538. void RequestGroup::validateFilename(const std::string& expectedFilename,
  539. const std::string& actualFilename) const
  540. {
  541. if(expectedFilename.empty()) {
  542. return;
  543. }
  544. if(expectedFilename != actualFilename) {
  545. throw DlAbortEx(StringFormat(EX_FILENAME_MISMATCH,
  546. expectedFilename.c_str(),
  547. actualFilename.c_str()).str());
  548. }
  549. }
  550. void RequestGroup::validateTotalLength(uint64_t expectedTotalLength,
  551. uint64_t actualTotalLength) const
  552. {
  553. if(expectedTotalLength <= 0) {
  554. return;
  555. }
  556. if(expectedTotalLength != actualTotalLength) {
  557. throw DlAbortEx
  558. (StringFormat(EX_SIZE_MISMATCH,
  559. Util::itos(expectedTotalLength, true).c_str(),
  560. Util::itos(actualTotalLength, true).c_str()).str());
  561. }
  562. }
  563. void RequestGroup::validateFilename(const std::string& actualFilename) const
  564. {
  565. validateFilename(_downloadContext->getFileEntries().front()->getBasename(), actualFilename);
  566. }
  567. void RequestGroup::validateTotalLength(uint64_t actualTotalLength) const
  568. {
  569. validateTotalLength(getTotalLength(), actualTotalLength);
  570. }
  571. void RequestGroup::increaseStreamConnection()
  572. {
  573. ++_numStreamConnection;
  574. }
  575. void RequestGroup::decreaseStreamConnection()
  576. {
  577. --_numStreamConnection;
  578. }
  579. unsigned int RequestGroup::getNumConnection() const
  580. {
  581. unsigned int numConnection = _numStreamConnection;
  582. #ifdef ENABLE_BITTORRENT
  583. {
  584. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  585. if(!btContext.isNull()) {
  586. BtRuntimeHandle btRuntime = BT_RUNTIME(btContext);
  587. if(!btRuntime.isNull()) {
  588. numConnection += btRuntime->getConnections();
  589. }
  590. }
  591. }
  592. #endif // ENABLE_BITTORRENT
  593. return numConnection;
  594. }
  595. void RequestGroup::increaseNumCommand()
  596. {
  597. ++_numCommand;
  598. }
  599. void RequestGroup::decreaseNumCommand()
  600. {
  601. --_numCommand;
  602. }
  603. TransferStat RequestGroup::calculateStat()
  604. {
  605. TransferStat stat;
  606. #ifdef ENABLE_BITTORRENT
  607. {
  608. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  609. if(!btContext.isNull()) {
  610. PeerStorageHandle peerStorage = PEER_STORAGE(btContext);
  611. if(!peerStorage.isNull()) {
  612. stat = peerStorage->calculateStat();
  613. }
  614. }
  615. }
  616. #endif // ENABLE_BITTORRENT
  617. if(!_segmentMan.isNull()) {
  618. stat.setDownloadSpeed(stat.getDownloadSpeed()+_segmentMan->calculateDownloadSpeed());
  619. }
  620. return stat;
  621. }
  622. void RequestGroup::setHaltRequested(bool f)
  623. {
  624. _haltRequested = f;
  625. #ifdef ENABLE_BITTORRENT
  626. {
  627. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  628. if(!btContext.isNull()) {
  629. BtRuntimeHandle btRuntime = BT_RUNTIME(btContext);
  630. if(!btRuntime.isNull()) {
  631. btRuntime->setHalt(f);
  632. }
  633. }
  634. }
  635. #endif // ENABLE_BITTORRENT
  636. }
  637. void RequestGroup::setForceHaltRequested(bool f)
  638. {
  639. setHaltRequested(f);
  640. _forceHaltRequested = f;
  641. }
  642. void RequestGroup::releaseRuntimeResource()
  643. {
  644. #ifdef ENABLE_BITTORRENT
  645. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  646. if(!btContext.isNull()) {
  647. BtContextHandle btContextInReg = BtRegistry::getBtContext(btContext->getInfoHashAsString());
  648. if(!btContextInReg.isNull() &&
  649. btContextInReg->getOwnerRequestGroup()->getGID() ==
  650. btContext->getOwnerRequestGroup()->getGID()) {
  651. BtRegistry::unregister(btContext->getInfoHashAsString());
  652. if(!DHTRegistry::_peerAnnounceStorage.isNull()) {
  653. DHTRegistry::_peerAnnounceStorage->removePeerAnnounce(btContext);
  654. }
  655. }
  656. }
  657. #endif // ENABLE_BITTORRENT
  658. if(!_pieceStorage.isNull()) {
  659. _pieceStorage->removeAdvertisedPiece(0);
  660. }
  661. }
  662. void RequestGroup::preDownloadProcessing()
  663. {
  664. _logger->debug("Finding PreDownloadHandler for path %s.", getFilePath().c_str());
  665. try {
  666. for(PreDownloadHandlers::const_iterator itr = _preDownloadHandlers.begin();
  667. itr != _preDownloadHandlers.end(); ++itr) {
  668. if((*itr)->canHandle(this)) {
  669. (*itr)->execute(this);
  670. return;
  671. }
  672. }
  673. } catch(RecoverableException& ex) {
  674. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  675. return;
  676. }
  677. _logger->debug("No PreDownloadHandler found.");
  678. return;
  679. }
  680. void RequestGroup::postDownloadProcessing
  681. (std::deque<SharedHandle<RequestGroup> >& groups)
  682. {
  683. _logger->debug("Finding PostDownloadHandler for path %s.", getFilePath().c_str());
  684. try {
  685. for(PostDownloadHandlers::const_iterator itr = _postDownloadHandlers.begin();
  686. itr != _postDownloadHandlers.end(); ++itr) {
  687. if((*itr)->canHandle(this)) {
  688. (*itr)->getNextRequestGroups(groups, this);
  689. return;
  690. }
  691. }
  692. } catch(RecoverableException& ex) {
  693. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  694. }
  695. _logger->debug("No PostDownloadHandler found.");
  696. }
  697. void RequestGroup::initializePreDownloadHandler()
  698. {
  699. #ifdef ENABLE_BITTORRENT
  700. if(_option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  701. _preDownloadHandlers.push_back(DownloadHandlerFactory::getBtPreDownloadHandler());
  702. }
  703. #endif // ENABLE_BITTORRENT
  704. #ifdef ENABLE_METALINK
  705. if(_option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  706. _preDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPreDownloadHandler());
  707. }
  708. #endif // ENABLE_METALINK
  709. }
  710. void RequestGroup::initializePostDownloadHandler()
  711. {
  712. #ifdef ENABLE_BITTORRENT
  713. if(_option->getAsBool(PREF_FOLLOW_TORRENT) ||
  714. _option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  715. _postDownloadHandlers.push_back(DownloadHandlerFactory::getBtPostDownloadHandler());
  716. }
  717. #endif // ENABLE_BITTORRENT
  718. #ifdef ENABLE_METALINK
  719. if(_option->getAsBool(PREF_FOLLOW_METALINK) ||
  720. _option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  721. _postDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPostDownloadHandler());
  722. }
  723. #endif // ENABLE_METALINK
  724. }
  725. void RequestGroup::getURIs(std::deque<std::string>& uris) const
  726. {
  727. uris.insert(uris.end(), _spentUris.begin(), _spentUris.end());
  728. uris.insert(uris.end(), _uris.begin(), _uris.end());
  729. }
  730. bool RequestGroup::isDependencyResolved()
  731. {
  732. if(_dependency.isNull()) {
  733. return true;
  734. }
  735. return _dependency->resolve();
  736. }
  737. void RequestGroup::setSegmentManFactory(const SegmentManFactoryHandle& segmentManFactory)
  738. {
  739. _segmentManFactory = segmentManFactory;
  740. }
  741. void RequestGroup::dependsOn(const DependencyHandle& dep)
  742. {
  743. _dependency = dep;
  744. }
  745. void RequestGroup::setDiskWriterFactory(const DiskWriterFactoryHandle& diskWriterFactory)
  746. {
  747. _diskWriterFactory = diskWriterFactory;
  748. }
  749. DiskWriterFactoryHandle RequestGroup::getDiskWriterFactory() const
  750. {
  751. return _diskWriterFactory;
  752. }
  753. void RequestGroup::addPostDownloadHandler(const PostDownloadHandlerHandle& handler)
  754. {
  755. _postDownloadHandlers.push_back(handler);
  756. }
  757. void RequestGroup::addPreDownloadHandler(const PreDownloadHandlerHandle& handler)
  758. {
  759. _preDownloadHandlers.push_back(handler);
  760. }
  761. void RequestGroup::clearPostDowloadHandler()
  762. {
  763. _postDownloadHandlers.clear();
  764. }
  765. void RequestGroup::clearPreDowloadHandler()
  766. {
  767. _preDownloadHandlers.clear();
  768. }
  769. SegmentManHandle RequestGroup::getSegmentMan() const
  770. {
  771. return _segmentMan;
  772. }
  773. DownloadContextHandle RequestGroup::getDownloadContext() const
  774. {
  775. return _downloadContext;
  776. }
  777. void RequestGroup::setDownloadContext(const DownloadContextHandle& downloadContext)
  778. {
  779. _downloadContext = downloadContext;
  780. }
  781. PieceStorageHandle RequestGroup::getPieceStorage() const
  782. {
  783. return _pieceStorage;
  784. }
  785. void RequestGroup::setPieceStorage(const PieceStorageHandle& pieceStorage)
  786. {
  787. _pieceStorage = pieceStorage;
  788. }
  789. BtProgressInfoFileHandle RequestGroup::getProgressInfoFile() const
  790. {
  791. return _progressInfoFile;
  792. }
  793. void RequestGroup::setProgressInfoFile(const BtProgressInfoFileHandle& progressInfoFile)
  794. {
  795. _progressInfoFile = progressInfoFile;
  796. }
  797. bool RequestGroup::needsFileAllocation() const
  798. {
  799. return isFileAllocationEnabled() &&
  800. (uint64_t)_option->getAsLLInt(PREF_NO_FILE_ALLOCATION_LIMIT) <= getTotalLength() &&
  801. !_pieceStorage->getDiskAdaptor()->fileAllocationIterator()->finished();
  802. }
  803. DownloadResultHandle RequestGroup::createDownloadResult() const
  804. {
  805. std::deque<std::string> uris;
  806. getURIs(uris);
  807. return
  808. SharedHandle<DownloadResult>(new DownloadResult(_gid,
  809. getFilePath(),
  810. getTotalLength(),
  811. uris.empty() ? A2STR::NIL:uris.front(),
  812. uris.size(),
  813. downloadFinished()?
  814. DownloadResult::FINISHED :
  815. DownloadResult::NOT_YET));
  816. }
  817. void RequestGroup::registerServerHost(const ServerHostHandle& serverHost)
  818. {
  819. _serverHosts.push_back(serverHost);
  820. }
  821. class FindServerHostByCUID
  822. {
  823. private:
  824. int32_t _cuid;
  825. public:
  826. FindServerHostByCUID(int32_t cuid):_cuid(cuid) {}
  827. bool operator()(const ServerHostHandle& sv) const
  828. {
  829. return sv->getCuid() == _cuid;
  830. }
  831. };
  832. ServerHostHandle RequestGroup::searchServerHost(int32_t cuid) const
  833. {
  834. std::deque<SharedHandle<ServerHost> >::const_iterator itr =
  835. std::find_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByCUID(cuid));
  836. if(itr == _serverHosts.end()) {
  837. return SharedHandle<ServerHost>();
  838. } else {
  839. return *itr;
  840. }
  841. }
  842. class FindServerHostByHostname
  843. {
  844. private:
  845. std::string _hostname;
  846. public:
  847. FindServerHostByHostname(const std::string& hostname):_hostname(hostname) {}
  848. bool operator()(const ServerHostHandle& sv) const
  849. {
  850. return sv->getHostname() == _hostname;
  851. }
  852. };
  853. ServerHostHandle RequestGroup::searchServerHost(const std::string& hostname) const
  854. {
  855. std::deque<SharedHandle<ServerHost> >::const_iterator itr =
  856. std::find_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByHostname(hostname));
  857. if(itr == _serverHosts.end()) {
  858. return SharedHandle<ServerHost>();
  859. } else {
  860. return *itr;
  861. }
  862. }
  863. void RequestGroup::removeServerHost(int32_t cuid)
  864. {
  865. _serverHosts.erase(std::remove_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByCUID(cuid)), _serverHosts.end());
  866. }
  867. void RequestGroup::removeURIWhoseHostnameIs(const std::string& hostname)
  868. {
  869. std::deque<std::string> newURIs;
  870. Request req;
  871. for(std::deque<std::string>::const_iterator itr = _uris.begin(); itr != _uris.end(); ++itr) {
  872. if(((*itr).find(hostname) == std::string::npos) ||
  873. (req.setUrl(*itr) && (req.getHost() != hostname))) {
  874. newURIs.push_back(*itr);
  875. }
  876. }
  877. _logger->debug("GUID#%d - Removed %d duplicate hostname URIs",
  878. _gid, _uris.size()-newURIs.size());
  879. _uris = newURIs;
  880. }
  881. void RequestGroup::removeIdenticalURI(const std::string& uri)
  882. {
  883. _uris.erase(std::remove(_uris.begin(), _uris.end(), uri), _uris.end());
  884. }
  885. void RequestGroup::reportDownloadFinished()
  886. {
  887. _logger->notice(MSG_FILE_DOWNLOAD_COMPLETED,
  888. getFilePath().c_str());
  889. #ifdef ENABLE_BITTORRENT
  890. TransferStat stat = calculateStat();
  891. SharedHandle<BtContext> ctx = dynamic_pointer_cast<BtContext>(_downloadContext);
  892. if(!ctx.isNull()) {
  893. double shareRatio = ((stat.getAllTimeUploadLength()*10)/getCompletedLength())/10.0;
  894. _logger->notice(MSG_SHARE_RATIO_REPORT,
  895. shareRatio,
  896. Util::abbrevSize(stat.getAllTimeUploadLength()).c_str(),
  897. Util::abbrevSize(getCompletedLength()).c_str());
  898. }
  899. #endif // ENABLE_BITTORRENT
  900. }
  901. const std::deque<std::string>& RequestGroup::getAcceptFeatures() const
  902. {
  903. return _acceptFeatures;
  904. }
  905. void RequestGroup::addAcceptFeatureHeader(const std::string& feature)
  906. {
  907. if(std::find(_acceptFeatures.begin(), _acceptFeatures.end(), feature) == _acceptFeatures.end()) {
  908. _acceptFeatures.push_back(feature);
  909. }
  910. }
  911. void RequestGroup::removeAcceptFeatureHeader(const std::string& feature)
  912. {
  913. std::deque<std::string>::iterator i = std::find(_acceptFeatures.begin(), _acceptFeatures.end(), feature);
  914. if(i != _acceptFeatures.end()) {
  915. _acceptFeatures.erase(i);
  916. }
  917. }
  918. const std::deque<std::string>& RequestGroup::getAcceptTypes() const
  919. {
  920. return _acceptTypes;
  921. }
  922. void RequestGroup::addAcceptType(const std::string& type)
  923. {
  924. if(std::find(_acceptTypes.begin(), _acceptTypes.end(), type) == _acceptTypes.end()) {
  925. _acceptTypes.push_back(type);
  926. }
  927. }
  928. void RequestGroup::removeAcceptType(const std::string& type)
  929. {
  930. _acceptTypes.erase(std::remove(_acceptTypes.begin(), _acceptTypes.end(), type),
  931. _acceptTypes.end());
  932. }
  933. void RequestGroup::setURISelector(const SharedHandle<URISelector>& uriSelector)
  934. {
  935. _uriSelector = uriSelector;
  936. }
  937. } // namespace aria2