RequestGroup.cc 31 KB

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