RequestGroup.cc 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "RequestGroup.h"
  36. #include <cassert>
  37. #include <algorithm>
  38. #include "PostDownloadHandler.h"
  39. #include "DownloadEngine.h"
  40. #include "DefaultSegmentManFactory.h"
  41. #include "SegmentMan.h"
  42. #include "NullProgressInfoFile.h"
  43. #include "Dependency.h"
  44. #include "prefs.h"
  45. #include "InitiateConnectionCommandFactory.h"
  46. #include "File.h"
  47. #include "message.h"
  48. #include "Util.h"
  49. #include "BtRegistry.h"
  50. #include "LogFactory.h"
  51. #include "Logger.h"
  52. #include "DiskAdaptor.h"
  53. #include "DiskWriterFactory.h"
  54. #include "RecoverableException.h"
  55. #include "StreamCheckIntegrityEntry.h"
  56. #include "CheckIntegrityCommand.h"
  57. #include "UnknownLengthPieceStorage.h"
  58. #include "BtContext.h"
  59. #include "SingleFileDownloadContext.h"
  60. #include "DlAbortEx.h"
  61. #include "DownloadFailureException.h"
  62. #include "RequestGroupMan.h"
  63. #include "DefaultBtProgressInfoFile.h"
  64. #include "DefaultPieceStorage.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. #include "PieceSelector.h"
  78. #ifdef ENABLE_MESSAGE_DIGEST
  79. # include "CheckIntegrityCommand.h"
  80. #endif // ENABLE_MESSAGE_DIGEST
  81. #ifdef ENABLE_BITTORRENT
  82. # include "BtCheckIntegrityEntry.h"
  83. # include "DefaultPeerStorage.h"
  84. # include "DefaultBtAnnounce.h"
  85. # include "BtRuntime.h"
  86. # include "BtSetup.h"
  87. # include "BtFileAllocationEntry.h"
  88. # include "BtPostDownloadHandler.h"
  89. # include "DHTSetup.h"
  90. # include "DHTRegistry.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. # include "LongestSequencePieceSelector.h"
  100. #endif // ENABLE_BITTORRENT
  101. #ifdef ENABLE_METALINK
  102. # include "MetalinkPostDownloadHandler.h"
  103. #endif // ENABLE_METALINK
  104. namespace aria2 {
  105. int32_t RequestGroup::_gidCounter = 0;
  106. const std::string RequestGroup::ACCEPT_METALINK = "application/metalink+xml";
  107. RequestGroup::RequestGroup(const Option* option,
  108. const std::deque<std::string>& uris):
  109. _gid(++_gidCounter),
  110. _uris(uris),
  111. _numConcurrentCommand(option->getAsInt(PREF_SPLIT)),
  112. _numStreamConnection(0),
  113. _numCommand(0),
  114. _segmentManFactory(new DefaultSegmentManFactory(option)),
  115. _progressInfoFile(new NullProgressInfoFile()),
  116. _preLocalFileCheckEnabled(true),
  117. _haltRequested(false),
  118. _forceHaltRequested(false),
  119. _singleHostMultiConnectionEnabled(true),
  120. _uriSelector(new InOrderURISelector()),
  121. _lastModifiedTime(Time::null()),
  122. _fileNotFoundCount(0),
  123. _inMemoryDownload(false),
  124. _option(option),
  125. _logger(LogFactory::getInstance())
  126. {
  127. if(_option->get(PREF_FILE_ALLOCATION) == V_PREALLOC) {
  128. _fileAllocationEnabled = true;
  129. } else {
  130. _fileAllocationEnabled = false;
  131. }
  132. // Add types to be sent as a Accept header value here.
  133. // It would be good to put this value in Option so that user can tweak
  134. // and add this list.
  135. // ACCEPT_METALINK is used for `transparent metalink'.
  136. addAcceptType(ACCEPT_METALINK);
  137. initializePreDownloadHandler();
  138. initializePostDownloadHandler();
  139. }
  140. RequestGroup::~RequestGroup() {}
  141. SegmentManHandle RequestGroup::initSegmentMan()
  142. {
  143. _segmentMan = _segmentManFactory->createNewInstance(_downloadContext,
  144. _pieceStorage);
  145. return _segmentMan;
  146. }
  147. bool RequestGroup::downloadFinished() const
  148. {
  149. if(_pieceStorage.isNull()) {
  150. return false;
  151. } else {
  152. return _pieceStorage->downloadFinished();
  153. }
  154. }
  155. bool RequestGroup::allDownloadFinished() const
  156. {
  157. if(_pieceStorage.isNull()) {
  158. return false;
  159. } else {
  160. return _pieceStorage->allDownloadFinished();
  161. }
  162. }
  163. DownloadResult::RESULT RequestGroup::downloadResult() const
  164. {
  165. if (downloadFinished())
  166. return DownloadResult::FINISHED;
  167. else {
  168. if (_uriResults.empty()) {
  169. return DownloadResult::UNKNOWN_ERROR;
  170. } else {
  171. return _uriResults.back().getResult();
  172. }
  173. }
  174. }
  175. void RequestGroup::closeFile()
  176. {
  177. if(!_pieceStorage.isNull()) {
  178. _pieceStorage->getDiskAdaptor()->closeFile();
  179. }
  180. }
  181. void RequestGroup::createInitialCommand(std::deque<Command*>& commands,
  182. DownloadEngine* e,
  183. const std::string& method)
  184. {
  185. #ifdef ENABLE_BITTORRENT
  186. {
  187. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  188. if(!btContext.isNull()) {
  189. if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
  190. throw DownloadFailureException
  191. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  192. getFilePath().c_str()).str());
  193. }
  194. initPieceStorage();
  195. if(btContext->getFileEntries().size() > 1) {
  196. // this is really multi file torrent.
  197. // clear http/ftp uris because the current implementation does not
  198. // allow integrating multi-file torrent and http/ftp.
  199. _logger->debug("Clearing http/ftp URIs because the current implementation does not allow integrating multi-file torrent and http/ftp.");
  200. _uris.clear();
  201. _pieceStorage->setFileFilter(Util::parseIntRange(_option->get(PREF_SELECT_FILE)));
  202. }
  203. SharedHandle<DefaultBtProgressInfoFile>
  204. progressInfoFile(new DefaultBtProgressInfoFile(_downloadContext,
  205. _pieceStorage,
  206. _option));
  207. SharedHandle<BtRegistry> btRegistry = e->getBtRegistry();
  208. btRegistry->registerBtContext(btContext->getInfoHashAsString(),
  209. btContext);
  210. btRegistry->registerPieceStorage(btContext->getInfoHashAsString(),
  211. _pieceStorage);
  212. btRegistry->registerBtProgressInfoFile(btContext->getInfoHashAsString(),
  213. progressInfoFile);
  214. BtRuntimeHandle btRuntime(new BtRuntime());
  215. btRuntime->setListenPort(_option->getAsInt(PREF_LISTEN_PORT));
  216. btRuntime->setMaxPeers(_option->getAsInt(PREF_BT_MAX_PEERS));
  217. btRegistry->registerBtRuntime(btContext->getInfoHashAsString(),
  218. btRuntime);
  219. _btRuntime = btRuntime;
  220. progressInfoFile->setBtRuntime(btRuntime);
  221. SharedHandle<DefaultPeerStorage> peerStorage
  222. (new DefaultPeerStorage(btContext, _option));
  223. peerStorage->setBtRuntime(btRuntime);
  224. peerStorage->setPieceStorage(_pieceStorage);
  225. btRegistry->registerPeerStorage(btContext->getInfoHashAsString(),
  226. peerStorage);
  227. _peerStorage = peerStorage;
  228. progressInfoFile->setPeerStorage(peerStorage);
  229. SharedHandle<DefaultBtAnnounce> btAnnounce
  230. (new DefaultBtAnnounce(btContext, _option));
  231. btAnnounce->setBtRuntime(btRuntime);
  232. btAnnounce->setPieceStorage(_pieceStorage);
  233. btAnnounce->setPeerStorage(peerStorage);
  234. btRegistry->registerBtAnnounce(btContext->getInfoHashAsString(),
  235. btAnnounce);
  236. btAnnounce->shuffleAnnounce();
  237. // Remove the control file if download file doesn't exist
  238. if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) {
  239. progressInfoFile->removeFile();
  240. _logger->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  241. progressInfoFile->getFilename().c_str(),
  242. _pieceStorage->getDiskAdaptor()->getFilePath().c_str());
  243. }
  244. // Call Load, Save and file allocation command here
  245. if(progressInfoFile->exists()) {
  246. // load .aria2 file if it exists.
  247. progressInfoFile->load();
  248. _pieceStorage->getDiskAdaptor()->openFile();
  249. } else {
  250. if(_pieceStorage->getDiskAdaptor()->fileExists()) {
  251. if(!_option->getAsBool(PREF_CHECK_INTEGRITY) &&
  252. !_option->getAsBool(PREF_ALLOW_OVERWRITE) &&
  253. !_option->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  254. // TODO we need this->haltRequested = true?
  255. throw DownloadFailureException
  256. (StringFormat
  257. (MSG_FILE_ALREADY_EXISTS,
  258. _pieceStorage->getDiskAdaptor()->getFilePath().c_str()).str());
  259. } else {
  260. _pieceStorage->getDiskAdaptor()->openFile();
  261. }
  262. if(_option->getAsBool(PREF_BT_SEED_UNVERIFIED)) {
  263. _pieceStorage->markAllPiecesDone();
  264. }
  265. } else {
  266. _pieceStorage->getDiskAdaptor()->openFile();
  267. }
  268. }
  269. _progressInfoFile = progressInfoFile;
  270. if(!btContext->isPrivate() && _option->getAsBool(PREF_ENABLE_DHT)) {
  271. std::deque<Command*> commands;
  272. DHTSetup().setup(commands, e, _option);
  273. e->addCommand(commands);
  274. if(!btContext->getNodes().empty() && DHTSetup::initialized()) {
  275. DHTEntryPointNameResolveCommand* command =
  276. new DHTEntryPointNameResolveCommand(e->newCUID(), e,
  277. btContext->getNodes());
  278. command->setTaskQueue(DHTRegistry::_taskQueue);
  279. command->setTaskFactory(DHTRegistry::_taskFactory);
  280. command->setRoutingTable(DHTRegistry::_routingTable);
  281. command->setLocalNode(DHTRegistry::_localNode);
  282. e->commands.push_back(command);
  283. }
  284. }
  285. CheckIntegrityEntryHandle entry(new BtCheckIntegrityEntry(this));
  286. // --bt-seed-unverified=true is given and download has completed, skip
  287. // validation for piece hashes.
  288. if(_option->getAsBool(PREF_BT_SEED_UNVERIFIED) &&
  289. _pieceStorage->downloadFinished()) {
  290. entry->onDownloadFinished(commands, e);
  291. } else {
  292. processCheckIntegrityEntry(commands, entry, e);
  293. }
  294. return;
  295. }
  296. }
  297. #endif // ENABLE_BITTORRENT
  298. // TODO I assume here when totallength is set to DownloadContext and it is
  299. // not 0, then filepath is also set DownloadContext correctly....
  300. if(_downloadContext->getTotalLength() == 0) {
  301. createNextCommand(commands, e, 1, method);
  302. }else {
  303. if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) {
  304. throw DownloadFailureException
  305. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  306. getFilePath().c_str()).str());
  307. }
  308. initPieceStorage();
  309. BtProgressInfoFileHandle infoFile
  310. (new DefaultBtProgressInfoFile(_downloadContext, _pieceStorage, _option));
  311. if(infoFile->exists() || !downloadFinishedByFileLength()) {
  312. loadAndOpenFile(infoFile);
  313. SharedHandle<CheckIntegrityEntry> checkIntegrityEntry
  314. (new StreamCheckIntegrityEntry(SharedHandle<Request>(), this));
  315. processCheckIntegrityEntry(commands, checkIntegrityEntry, e);
  316. }
  317. }
  318. }
  319. void RequestGroup::processCheckIntegrityEntry(std::deque<Command*>& commands,
  320. const CheckIntegrityEntryHandle& entry,
  321. DownloadEngine* e)
  322. {
  323. #ifdef ENABLE_MESSAGE_DIGEST
  324. if(e->option->getAsBool(PREF_CHECK_INTEGRITY) &&
  325. entry->isValidationReady()) {
  326. entry->initValidator();
  327. entry->cutTrailingGarbage();
  328. e->_checkIntegrityMan->pushEntry(entry);
  329. } else
  330. #endif // ENABLE_MESSAGE_DIGEST
  331. {
  332. entry->onDownloadIncomplete(commands, e);
  333. }
  334. }
  335. void RequestGroup::initPieceStorage()
  336. {
  337. if(_downloadContext->knowsTotalLength()) {
  338. #ifdef ENABLE_BITTORRENT
  339. SharedHandle<DefaultPieceStorage> ps;
  340. SharedHandle<PieceSelector> selector;
  341. // Use LongestSequencePieceSelector when HTTP/FTP/BitTorrent integrated
  342. // downloads. Currently multi-file integrated download is not supported.
  343. if(!_uris.empty() &&
  344. _downloadContext->getFileEntries().size() == 1 &&
  345. !dynamic_pointer_cast<BtContext>(_downloadContext).isNull()) {
  346. _logger->debug("Using LongestSequencePieceSelector");
  347. selector.reset(new LongestSequencePieceSelector());
  348. }
  349. ps.reset(new DefaultPieceStorage(_downloadContext, _option, selector));
  350. #else // !ENABLE_BITTORRENT
  351. SharedHandle<DefaultPieceStorage> ps
  352. (new DefaultPieceStorage(_downloadContext, _option));
  353. #endif // !ENABLE_BITTORRENT
  354. if(!_diskWriterFactory.isNull()) {
  355. ps->setDiskWriterFactory(_diskWriterFactory);
  356. }
  357. _pieceStorage = ps;
  358. } else {
  359. UnknownLengthPieceStorageHandle ps
  360. (new UnknownLengthPieceStorage(_downloadContext, _option));
  361. if(!_diskWriterFactory.isNull()) {
  362. ps->setDiskWriterFactory(_diskWriterFactory);
  363. }
  364. _pieceStorage = ps;
  365. }
  366. _pieceStorage->initStorage();
  367. initSegmentMan();
  368. }
  369. bool RequestGroup::downloadFinishedByFileLength()
  370. {
  371. // assuming that a control file doesn't exist.
  372. if(!isPreLocalFileCheckEnabled() ||
  373. _option->getAsBool(PREF_ALLOW_OVERWRITE) ||
  374. (_option->getAsBool(PREF_CHECK_INTEGRITY) &&
  375. !_downloadContext->getPieceHashes().empty())) {
  376. return false;
  377. }
  378. // TODO consider the case when the getFilePath() returns dir path.
  379. File outfile(getFilePath());
  380. if(outfile.exists() && getTotalLength() == outfile.size()) {
  381. _pieceStorage->markAllPiecesDone();
  382. _logger->notice(MSG_DOWNLOAD_ALREADY_COMPLETED, _gid, getFilePath().c_str());
  383. return true;
  384. } else {
  385. return false;
  386. }
  387. }
  388. void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoFile)
  389. {
  390. try {
  391. if(!isPreLocalFileCheckEnabled()) {
  392. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  393. return;
  394. }
  395. // Remove the control file if download file doesn't exist
  396. if(progressInfoFile->exists() && !_pieceStorage->getDiskAdaptor()->fileExists()) {
  397. progressInfoFile->removeFile();
  398. _logger->notice(MSG_REMOVED_DEFUNCT_CONTROL_FILE,
  399. progressInfoFile->getFilename().c_str(),
  400. _pieceStorage->getDiskAdaptor()->getFilePath().c_str());
  401. }
  402. while(1) {
  403. if(progressInfoFile->exists()) {
  404. progressInfoFile->load();
  405. _pieceStorage->getDiskAdaptor()->openExistingFile();
  406. } else {
  407. File outfile(getFilePath());
  408. if(outfile.exists() && _option->getAsBool(PREF_CONTINUE) &&
  409. outfile.size() <= getTotalLength()) {
  410. _pieceStorage->getDiskAdaptor()->openExistingFile();
  411. _pieceStorage->markPiecesDone(outfile.size());
  412. } else {
  413. #ifdef ENABLE_MESSAGE_DIGEST
  414. if(outfile.exists() && _option->getAsBool(PREF_CHECK_INTEGRITY)) {
  415. _pieceStorage->getDiskAdaptor()->openExistingFile();
  416. } else {
  417. #endif // ENABLE_MESSAGE_DIGEST
  418. shouldCancelDownloadForSafety();
  419. // call updateFilename here in case when filename is renamed
  420. // by tryAutoFileRenaming()
  421. progressInfoFile->updateFilename();
  422. if(progressInfoFile->exists()) {
  423. // Close DiskAdaptor here. Renmaed file will be opened in the
  424. // next loop .
  425. _pieceStorage->getDiskAdaptor()->closeFile();
  426. continue;
  427. }
  428. _pieceStorage->getDiskAdaptor()->initAndOpenFile();
  429. #ifdef ENABLE_MESSAGE_DIGEST
  430. }
  431. #endif // ENABLE_MESSAGE_DIGEST
  432. }
  433. }
  434. setProgressInfoFile(progressInfoFile);
  435. break;
  436. }
  437. } catch(RecoverableException& e) {
  438. throw DownloadFailureException
  439. (StringFormat(EX_DOWNLOAD_ABORTED).str(), e);
  440. }
  441. }
  442. // assuming that a control file does not exist
  443. void RequestGroup::shouldCancelDownloadForSafety()
  444. {
  445. if(_option->getAsBool(PREF_ALLOW_OVERWRITE)) {
  446. return;
  447. }
  448. File outfile(getFilePath());
  449. if(outfile.exists()) {
  450. if(_option->getAsBool(PREF_AUTO_FILE_RENAMING)) {
  451. if(tryAutoFileRenaming()) {
  452. _logger->notice(MSG_FILE_RENAMED, getFilePath().c_str());
  453. } else {
  454. throw DownloadFailureException
  455. (StringFormat("File renaming failed: %s",
  456. getFilePath().c_str()).str());
  457. }
  458. } else {
  459. throw DownloadFailureException
  460. (StringFormat(MSG_FILE_ALREADY_EXISTS,
  461. getFilePath().c_str()).str());
  462. }
  463. }
  464. }
  465. bool RequestGroup::tryAutoFileRenaming()
  466. {
  467. std::string filepath = getFilePath();
  468. if(filepath.empty()) {
  469. return false;
  470. }
  471. SingleFileDownloadContextHandle ctx =
  472. dynamic_pointer_cast<SingleFileDownloadContext>(_downloadContext);
  473. // Make a copy of ctx.
  474. SingleFileDownloadContextHandle tempCtx(new SingleFileDownloadContext(*ctx.get()));
  475. DefaultBtProgressInfoFile tempInfoFile(tempCtx, SharedHandle<PieceStorage>(), 0);
  476. for(unsigned int i = 1; i < 10000; ++i) {
  477. File newfile(filepath+"."+Util::uitos(i));
  478. std::string newFilename = newfile.getBasename();
  479. tempCtx->setUFilename(newFilename);
  480. tempInfoFile.updateFilename();
  481. if(!newfile.exists() || (newfile.exists() && tempInfoFile.exists())) {
  482. ctx->setUFilename(newFilename);
  483. return true;
  484. }
  485. }
  486. return false;
  487. }
  488. void RequestGroup::createNextCommandWithAdj(std::deque<Command*>& commands,
  489. DownloadEngine* e, int numAdj)
  490. {
  491. int numCommand;
  492. if(getTotalLength() == 0) {
  493. numCommand = 1+numAdj;
  494. } else {
  495. if(_numConcurrentCommand == 0) {
  496. // TODO remove _uris.size() support
  497. numCommand = _uris.size();
  498. } else {
  499. numCommand = _numConcurrentCommand;
  500. }
  501. numCommand = std::min(static_cast<int>(_downloadContext->getNumPieces()),
  502. numCommand);
  503. numCommand += numAdj;
  504. }
  505. if(numCommand > 0) {
  506. createNextCommand(commands, e, numCommand);
  507. }
  508. }
  509. void RequestGroup::createNextCommand(std::deque<Command*>& commands,
  510. DownloadEngine* e,
  511. unsigned int numCommand,
  512. const std::string& method)
  513. {
  514. std::deque<std::string> pendingURIs;
  515. for(; !_uris.empty() && numCommand--; ) {
  516. std::string uri = _uriSelector->select(_uris);
  517. if(uri.empty())
  518. continue;
  519. RequestHandle req(new Request());
  520. if(req->setUrl(uri)) {
  521. ServerHostHandle sv;
  522. if(!_singleHostMultiConnectionEnabled){
  523. sv = searchServerHost(req->getHost());
  524. }
  525. if(sv.isNull()) {
  526. _spentUris.push_back(uri);
  527. req->setReferer(_option->get(PREF_REFERER));
  528. req->setMethod(method);
  529. Command* command =
  530. InitiateConnectionCommandFactory::createInitiateConnectionCommand
  531. (e->newCUID(), req, this, e);
  532. ServerHostHandle sv(new ServerHost(command->getCuid(), req->getHost()));
  533. registerServerHost(sv);
  534. // give a chance to be executed in the next loop in DownloadEngine
  535. command->setStatus(Command::STATUS_ONESHOT_REALTIME);
  536. commands.push_back(command);
  537. } else {
  538. pendingURIs.push_back(uri);
  539. }
  540. } else {
  541. _logger->error(MSG_UNRECOGNIZED_URI, req->getUrl().c_str());
  542. }
  543. }
  544. _uris.insert(_uris.begin(), pendingURIs.begin(), pendingURIs.end());
  545. }
  546. std::string RequestGroup::getFilePath() const
  547. {
  548. assert(!_downloadContext.isNull());
  549. if(inMemoryDownload()) {
  550. static const std::string DIR_MEMORY("[MEMORY]");
  551. return DIR_MEMORY+File(_downloadContext->getActualBasePath()).getBasename();
  552. } else {
  553. return _downloadContext->getActualBasePath();
  554. }
  555. }
  556. uint64_t RequestGroup::getTotalLength() const
  557. {
  558. if(_pieceStorage.isNull()) {
  559. return 0;
  560. } else {
  561. if(_pieceStorage->isSelectiveDownloadingMode()) {
  562. return _pieceStorage->getFilteredTotalLength();
  563. } else {
  564. return _pieceStorage->getTotalLength();
  565. }
  566. }
  567. }
  568. uint64_t RequestGroup::getCompletedLength() const
  569. {
  570. if(_pieceStorage.isNull()) {
  571. return 0;
  572. } else {
  573. if(_pieceStorage->isSelectiveDownloadingMode()) {
  574. return _pieceStorage->getFilteredCompletedLength();
  575. } else {
  576. return _pieceStorage->getCompletedLength();
  577. }
  578. }
  579. }
  580. void RequestGroup::validateFilename(const std::string& expectedFilename,
  581. const std::string& actualFilename) const
  582. {
  583. if(expectedFilename.empty()) {
  584. return;
  585. }
  586. if(expectedFilename != actualFilename) {
  587. throw DlAbortEx(StringFormat(EX_FILENAME_MISMATCH,
  588. expectedFilename.c_str(),
  589. actualFilename.c_str()).str());
  590. }
  591. }
  592. void RequestGroup::validateTotalLength(uint64_t expectedTotalLength,
  593. uint64_t actualTotalLength) const
  594. {
  595. if(expectedTotalLength <= 0) {
  596. return;
  597. }
  598. if(expectedTotalLength != actualTotalLength) {
  599. throw DlAbortEx
  600. (StringFormat(EX_SIZE_MISMATCH,
  601. Util::itos(expectedTotalLength, true).c_str(),
  602. Util::itos(actualTotalLength, true).c_str()).str());
  603. }
  604. }
  605. void RequestGroup::validateFilename(const std::string& actualFilename) const
  606. {
  607. validateFilename(_downloadContext->getFileEntries().front()->getBasename(), actualFilename);
  608. }
  609. void RequestGroup::validateTotalLength(uint64_t actualTotalLength) const
  610. {
  611. validateTotalLength(getTotalLength(), actualTotalLength);
  612. }
  613. void RequestGroup::increaseStreamConnection()
  614. {
  615. ++_numStreamConnection;
  616. }
  617. void RequestGroup::decreaseStreamConnection()
  618. {
  619. --_numStreamConnection;
  620. }
  621. unsigned int RequestGroup::getNumConnection() const
  622. {
  623. unsigned int numConnection = _numStreamConnection;
  624. #ifdef ENABLE_BITTORRENT
  625. if(!_btRuntime.isNull()) {
  626. numConnection += _btRuntime->getConnections();
  627. }
  628. #endif // ENABLE_BITTORRENT
  629. return numConnection;
  630. }
  631. void RequestGroup::increaseNumCommand()
  632. {
  633. ++_numCommand;
  634. }
  635. void RequestGroup::decreaseNumCommand()
  636. {
  637. --_numCommand;
  638. }
  639. TransferStat RequestGroup::calculateStat()
  640. {
  641. TransferStat stat;
  642. #ifdef ENABLE_BITTORRENT
  643. if(!_peerStorage.isNull()) {
  644. stat = _peerStorage->calculateStat();
  645. }
  646. #endif // ENABLE_BITTORRENT
  647. if(!_segmentMan.isNull()) {
  648. stat.setDownloadSpeed(stat.getDownloadSpeed()+_segmentMan->calculateDownloadSpeed());
  649. }
  650. return stat;
  651. }
  652. void RequestGroup::setHaltRequested(bool f)
  653. {
  654. _haltRequested = f;
  655. #ifdef ENABLE_BITTORRENT
  656. if(!_btRuntime.isNull()) {
  657. _btRuntime->setHalt(f);
  658. }
  659. #endif // ENABLE_BITTORRENT
  660. }
  661. void RequestGroup::setForceHaltRequested(bool f)
  662. {
  663. setHaltRequested(f);
  664. _forceHaltRequested = f;
  665. }
  666. void RequestGroup::releaseRuntimeResource(DownloadEngine* e)
  667. {
  668. #ifdef ENABLE_BITTORRENT
  669. BtContextHandle btContext = dynamic_pointer_cast<BtContext>(_downloadContext);
  670. if(!btContext.isNull()) {
  671. SharedHandle<BtRegistry> btRegistry = e->getBtRegistry();
  672. BtContextHandle btContextInReg =
  673. btRegistry->getBtContext(btContext->getInfoHashAsString());
  674. if(!btContextInReg.isNull() &&
  675. btContextInReg->getOwnerRequestGroup()->getGID() ==
  676. btContext->getOwnerRequestGroup()->getGID()) {
  677. btRegistry->unregister(btContext->getInfoHashAsString());
  678. if(!DHTRegistry::_peerAnnounceStorage.isNull()) {
  679. DHTRegistry::_peerAnnounceStorage->
  680. removeLocalPeerAnnounce(btContext->getInfoHash());
  681. }
  682. }
  683. }
  684. #endif // ENABLE_BITTORRENT
  685. if(!_pieceStorage.isNull()) {
  686. _pieceStorage->removeAdvertisedPiece(0);
  687. }
  688. }
  689. void RequestGroup::preDownloadProcessing()
  690. {
  691. _logger->debug("Finding PreDownloadHandler for path %s.", getFilePath().c_str());
  692. try {
  693. for(PreDownloadHandlers::const_iterator itr = _preDownloadHandlers.begin();
  694. itr != _preDownloadHandlers.end(); ++itr) {
  695. if((*itr)->canHandle(this)) {
  696. (*itr)->execute(this);
  697. return;
  698. }
  699. }
  700. } catch(RecoverableException& ex) {
  701. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  702. return;
  703. }
  704. _logger->debug("No PreDownloadHandler found.");
  705. return;
  706. }
  707. void RequestGroup::postDownloadProcessing
  708. (std::deque<SharedHandle<RequestGroup> >& groups)
  709. {
  710. _logger->debug("Finding PostDownloadHandler for path %s.", getFilePath().c_str());
  711. try {
  712. for(PostDownloadHandlers::const_iterator itr = _postDownloadHandlers.begin();
  713. itr != _postDownloadHandlers.end(); ++itr) {
  714. if((*itr)->canHandle(this)) {
  715. (*itr)->getNextRequestGroups(groups, this);
  716. return;
  717. }
  718. }
  719. } catch(RecoverableException& ex) {
  720. _logger->error(EX_EXCEPTION_CAUGHT, ex);
  721. }
  722. _logger->debug("No PostDownloadHandler found.");
  723. }
  724. void RequestGroup::initializePreDownloadHandler()
  725. {
  726. #ifdef ENABLE_BITTORRENT
  727. if(_option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  728. _preDownloadHandlers.push_back(DownloadHandlerFactory::getBtPreDownloadHandler());
  729. }
  730. #endif // ENABLE_BITTORRENT
  731. #ifdef ENABLE_METALINK
  732. if(_option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  733. _preDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPreDownloadHandler());
  734. }
  735. #endif // ENABLE_METALINK
  736. }
  737. void RequestGroup::initializePostDownloadHandler()
  738. {
  739. #ifdef ENABLE_BITTORRENT
  740. if(_option->getAsBool(PREF_FOLLOW_TORRENT) ||
  741. _option->get(PREF_FOLLOW_TORRENT) == V_MEM) {
  742. _postDownloadHandlers.push_back(DownloadHandlerFactory::getBtPostDownloadHandler());
  743. }
  744. #endif // ENABLE_BITTORRENT
  745. #ifdef ENABLE_METALINK
  746. if(_option->getAsBool(PREF_FOLLOW_METALINK) ||
  747. _option->get(PREF_FOLLOW_METALINK) == V_MEM) {
  748. _postDownloadHandlers.push_back(DownloadHandlerFactory::getMetalinkPostDownloadHandler());
  749. }
  750. #endif // ENABLE_METALINK
  751. }
  752. void RequestGroup::getURIs(std::deque<std::string>& uris) const
  753. {
  754. uris.insert(uris.end(), _spentUris.begin(), _spentUris.end());
  755. uris.insert(uris.end(), _uris.begin(), _uris.end());
  756. }
  757. bool RequestGroup::isDependencyResolved()
  758. {
  759. if(_dependency.isNull()) {
  760. return true;
  761. }
  762. return _dependency->resolve();
  763. }
  764. void RequestGroup::setSegmentManFactory(const SegmentManFactoryHandle& segmentManFactory)
  765. {
  766. _segmentManFactory = segmentManFactory;
  767. }
  768. void RequestGroup::dependsOn(const DependencyHandle& dep)
  769. {
  770. _dependency = dep;
  771. }
  772. void RequestGroup::setDiskWriterFactory(const DiskWriterFactoryHandle& diskWriterFactory)
  773. {
  774. _diskWriterFactory = diskWriterFactory;
  775. }
  776. DiskWriterFactoryHandle RequestGroup::getDiskWriterFactory() const
  777. {
  778. return _diskWriterFactory;
  779. }
  780. void RequestGroup::addPostDownloadHandler(const PostDownloadHandlerHandle& handler)
  781. {
  782. _postDownloadHandlers.push_back(handler);
  783. }
  784. void RequestGroup::addPreDownloadHandler(const PreDownloadHandlerHandle& handler)
  785. {
  786. _preDownloadHandlers.push_back(handler);
  787. }
  788. void RequestGroup::clearPostDowloadHandler()
  789. {
  790. _postDownloadHandlers.clear();
  791. }
  792. void RequestGroup::clearPreDowloadHandler()
  793. {
  794. _preDownloadHandlers.clear();
  795. }
  796. SegmentManHandle RequestGroup::getSegmentMan() const
  797. {
  798. return _segmentMan;
  799. }
  800. DownloadContextHandle RequestGroup::getDownloadContext() const
  801. {
  802. return _downloadContext;
  803. }
  804. void RequestGroup::setDownloadContext(const DownloadContextHandle& downloadContext)
  805. {
  806. _downloadContext = downloadContext;
  807. }
  808. PieceStorageHandle RequestGroup::getPieceStorage() const
  809. {
  810. return _pieceStorage;
  811. }
  812. void RequestGroup::setPieceStorage(const PieceStorageHandle& pieceStorage)
  813. {
  814. _pieceStorage = pieceStorage;
  815. }
  816. BtProgressInfoFileHandle RequestGroup::getProgressInfoFile() const
  817. {
  818. return _progressInfoFile;
  819. }
  820. void RequestGroup::setProgressInfoFile(const BtProgressInfoFileHandle& progressInfoFile)
  821. {
  822. _progressInfoFile = progressInfoFile;
  823. }
  824. bool RequestGroup::needsFileAllocation() const
  825. {
  826. return isFileAllocationEnabled() &&
  827. (uint64_t)_option->getAsLLInt(PREF_NO_FILE_ALLOCATION_LIMIT) <= getTotalLength() &&
  828. !_pieceStorage->getDiskAdaptor()->fileAllocationIterator()->finished();
  829. }
  830. DownloadResultHandle RequestGroup::createDownloadResult() const
  831. {
  832. std::deque<std::string> uris;
  833. getURIs(uris);
  834. uint64_t sessionDownloadLength = 0;
  835. #ifdef ENABLE_BITTORRENT
  836. if(!_peerStorage.isNull()) {
  837. sessionDownloadLength +=
  838. _peerStorage->calculateStat().getSessionDownloadLength();
  839. }
  840. #endif // ENABLE_BITTORRENT
  841. if(!_segmentMan.isNull()) {
  842. sessionDownloadLength +=
  843. _segmentMan->calculateSessionDownloadLength();
  844. }
  845. return
  846. SharedHandle<DownloadResult>
  847. (new DownloadResult(_gid,
  848. getFilePath(),
  849. getTotalLength(),
  850. uris.empty() ? A2STR::NIL:uris.front(),
  851. uris.size(),
  852. sessionDownloadLength,
  853. _downloadContext->calculateSessionTime(),
  854. downloadResult()));
  855. }
  856. void RequestGroup::registerServerHost(const ServerHostHandle& serverHost)
  857. {
  858. _serverHosts.push_back(serverHost);
  859. }
  860. class FindServerHostByCUID
  861. {
  862. private:
  863. int32_t _cuid;
  864. public:
  865. FindServerHostByCUID(int32_t cuid):_cuid(cuid) {}
  866. bool operator()(const ServerHostHandle& sv) const
  867. {
  868. return sv->getCuid() == _cuid;
  869. }
  870. };
  871. ServerHostHandle RequestGroup::searchServerHost(int32_t cuid) const
  872. {
  873. std::deque<SharedHandle<ServerHost> >::const_iterator itr =
  874. std::find_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByCUID(cuid));
  875. if(itr == _serverHosts.end()) {
  876. return SharedHandle<ServerHost>();
  877. } else {
  878. return *itr;
  879. }
  880. }
  881. class FindServerHostByHostname
  882. {
  883. private:
  884. std::string _hostname;
  885. public:
  886. FindServerHostByHostname(const std::string& hostname):_hostname(hostname) {}
  887. bool operator()(const ServerHostHandle& sv) const
  888. {
  889. return sv->getHostname() == _hostname;
  890. }
  891. };
  892. ServerHostHandle RequestGroup::searchServerHost(const std::string& hostname) const
  893. {
  894. std::deque<SharedHandle<ServerHost> >::const_iterator itr =
  895. std::find_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByHostname(hostname));
  896. if(itr == _serverHosts.end()) {
  897. return SharedHandle<ServerHost>();
  898. } else {
  899. return *itr;
  900. }
  901. }
  902. void RequestGroup::removeServerHost(int32_t cuid)
  903. {
  904. _serverHosts.erase(std::remove_if(_serverHosts.begin(), _serverHosts.end(), FindServerHostByCUID(cuid)), _serverHosts.end());
  905. }
  906. void RequestGroup::removeURIWhoseHostnameIs(const std::string& hostname)
  907. {
  908. std::deque<std::string> newURIs;
  909. Request req;
  910. for(std::deque<std::string>::const_iterator itr = _uris.begin(); itr != _uris.end(); ++itr) {
  911. if(((*itr).find(hostname) == std::string::npos) ||
  912. (req.setUrl(*itr) && (req.getHost() != hostname))) {
  913. newURIs.push_back(*itr);
  914. }
  915. }
  916. _logger->debug("GUID#%d - Removed %d duplicate hostname URIs",
  917. _gid, _uris.size()-newURIs.size());
  918. _uris = newURIs;
  919. }
  920. void RequestGroup::removeIdenticalURI(const std::string& uri)
  921. {
  922. _uris.erase(std::remove(_uris.begin(), _uris.end(), uri), _uris.end());
  923. }
  924. void RequestGroup::reportDownloadFinished()
  925. {
  926. _logger->notice(MSG_FILE_DOWNLOAD_COMPLETED,
  927. getFilePath().c_str());
  928. _uriSelector->resetCounters();
  929. #ifdef ENABLE_BITTORRENT
  930. SharedHandle<BtContext> ctx = dynamic_pointer_cast<BtContext>(_downloadContext);
  931. if(!ctx.isNull()) {
  932. TransferStat stat = calculateStat();
  933. double shareRatio = ((stat.getAllTimeUploadLength()*10)/getCompletedLength())/10.0;
  934. _logger->notice(MSG_SHARE_RATIO_REPORT,
  935. shareRatio,
  936. Util::abbrevSize(stat.getAllTimeUploadLength()).c_str(),
  937. Util::abbrevSize(getCompletedLength()).c_str());
  938. }
  939. #endif // ENABLE_BITTORRENT
  940. }
  941. const std::deque<std::string>& RequestGroup::getAcceptFeatures() const
  942. {
  943. return _acceptFeatures;
  944. }
  945. void RequestGroup::addAcceptFeatureHeader(const std::string& feature)
  946. {
  947. if(std::find(_acceptFeatures.begin(), _acceptFeatures.end(), feature) == _acceptFeatures.end()) {
  948. _acceptFeatures.push_back(feature);
  949. }
  950. }
  951. void RequestGroup::removeAcceptFeatureHeader(const std::string& feature)
  952. {
  953. std::deque<std::string>::iterator i = std::find(_acceptFeatures.begin(), _acceptFeatures.end(), feature);
  954. if(i != _acceptFeatures.end()) {
  955. _acceptFeatures.erase(i);
  956. }
  957. }
  958. const std::deque<std::string>& RequestGroup::getAcceptTypes() const
  959. {
  960. return _acceptTypes;
  961. }
  962. void RequestGroup::addAcceptType(const std::string& type)
  963. {
  964. if(std::find(_acceptTypes.begin(), _acceptTypes.end(), type) == _acceptTypes.end()) {
  965. _acceptTypes.push_back(type);
  966. }
  967. }
  968. void RequestGroup::removeAcceptType(const std::string& type)
  969. {
  970. _acceptTypes.erase(std::remove(_acceptTypes.begin(), _acceptTypes.end(), type),
  971. _acceptTypes.end());
  972. }
  973. void RequestGroup::setURISelector(const SharedHandle<URISelector>& uriSelector)
  974. {
  975. _uriSelector = uriSelector;
  976. }
  977. void RequestGroup::applyLastModifiedTimeToLocalFiles()
  978. {
  979. if(!_pieceStorage.isNull() && _lastModifiedTime.good()) {
  980. time_t t = _lastModifiedTime.getTime();
  981. _logger->info("Applying Last-Modified time: %s in local time zone",
  982. ctime(&t));
  983. size_t n =
  984. _pieceStorage->getDiskAdaptor()->utime(Time(), _lastModifiedTime);
  985. _logger->info("Last-Modified attrs of %lu files were updated.",
  986. static_cast<unsigned long>(n));
  987. }
  988. }
  989. void RequestGroup::updateLastModifiedTime(const Time& time)
  990. {
  991. if(time.good() && _lastModifiedTime < time) {
  992. _lastModifiedTime = time;
  993. }
  994. }
  995. void RequestGroup::increaseAndValidateFileNotFoundCount()
  996. {
  997. ++_fileNotFoundCount;
  998. const unsigned int maxCount = _option->getAsInt(PREF_MAX_FILE_NOT_FOUND);
  999. if(maxCount > 0 && _fileNotFoundCount >= maxCount &&
  1000. _segmentMan->calculateSessionDownloadLength() == 0) {
  1001. throw DownloadFailureException
  1002. (StringFormat("Reached max-file-not-found count=%u", maxCount).str(),
  1003. DownloadResult::MAX_FILE_NOT_FOUND);
  1004. }
  1005. }
  1006. unsigned int RequestGroup::getNumConcurrentCommand() const
  1007. {
  1008. return _numConcurrentCommand;
  1009. }
  1010. void RequestGroup::markInMemoryDownload()
  1011. {
  1012. _inMemoryDownload = true;
  1013. }
  1014. bool RequestGroup::inMemoryDownload() const
  1015. {
  1016. return _inMemoryDownload;
  1017. }
  1018. void RequestGroup::tuneDownloadCommand(DownloadCommand* command)
  1019. {
  1020. _uriSelector->tuneDownloadCommand(_uris, command);
  1021. }
  1022. void RequestGroup::addURIResult(std::string uri, DownloadResult::RESULT result)
  1023. {
  1024. _uriResults.push_back(URIResult(uri, result));
  1025. }
  1026. const std::deque<URIResult>& RequestGroup::getURIResults() const
  1027. {
  1028. return _uriResults;
  1029. }
  1030. } // namespace aria2