AbstractCommand.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 "AbstractCommand.h"
  36. #include "SegmentMan.h"
  37. #include "NameResolver.h"
  38. #include "CUIDCounter.h"
  39. #include "DlAbortEx.h"
  40. #include "DlRetryEx.h"
  41. #include "FatalException.h"
  42. #include "InitiateConnectionCommandFactory.h"
  43. #include "Util.h"
  44. #include "message.h"
  45. #include "SleepCommand.h"
  46. #include "prefs.h"
  47. #include "DNSCache.h"
  48. #include "SingleFileDownloadContext.h"
  49. #include "DefaultPieceStorage.h"
  50. #include "UnknownLengthPieceStorage.h"
  51. #include "File.h"
  52. #include "StreamCheckIntegrityEntry.h"
  53. #include "DefaultBtProgressInfoFile.h"
  54. #include "CheckIntegrityCommand.h"
  55. #include "DiskAdaptor.h"
  56. #include "PeerStat.h"
  57. #include "Segment.h"
  58. #include "DiskWriterFactory.h"
  59. #include "Option.h"
  60. AbstractCommand::AbstractCommand(int32_t cuid,
  61. const RequestHandle& req,
  62. RequestGroup* requestGroup,
  63. DownloadEngine* e,
  64. const SocketHandle& s):
  65. Command(cuid), RequestGroupAware(requestGroup),
  66. req(req), e(e), socket(s),
  67. checkSocketIsReadable(false), checkSocketIsWritable(false),
  68. nameResolverCheck(false)
  69. {
  70. setReadCheckSocket(socket);
  71. timeout = this->e->option->getAsInt(PREF_TIMEOUT);
  72. _requestGroup->increaseStreamConnection();
  73. }
  74. AbstractCommand::~AbstractCommand() {
  75. disableReadCheckSocket();
  76. disableWriteCheckSocket();
  77. _requestGroup->decreaseStreamConnection();
  78. }
  79. bool AbstractCommand::execute() {
  80. try {
  81. if(_requestGroup->downloadFinished() || _requestGroup->isHaltRequested()) {
  82. //logger->debug("CUID#%d - finished.", cuid);
  83. return true;
  84. }
  85. PeerStatHandle peerStat = 0;
  86. if(!_requestGroup->getSegmentMan().isNull()) {
  87. peerStat = _requestGroup->getSegmentMan()->getPeerStat(cuid);
  88. }
  89. if(!peerStat.isNull()) {
  90. if(peerStat->getStatus() == PeerStat::REQUEST_IDLE) {
  91. logger->info(MSG_ABORT_REQUESTED, cuid);
  92. onAbort(0);
  93. req->resetUrl();
  94. tryReserved();
  95. return true;
  96. }
  97. }
  98. if(checkSocketIsReadable && readCheckTarget->isReadable(0) ||
  99. checkSocketIsWritable && writeCheckTarget->isWritable(0) ||
  100. #ifdef ENABLE_ASYNC_DNS
  101. nameResolverCheck && nameResolveFinished() ||
  102. #endif // ENABLE_ASYNC_DNS
  103. !checkSocketIsReadable && !checkSocketIsWritable && !nameResolverCheck) {
  104. checkPoint.reset();
  105. if(!_requestGroup->getPieceStorage().isNull()) {
  106. _segments = _requestGroup->getSegmentMan()->getInFlightSegment(cuid);
  107. int32_t maxSegments;
  108. if(req->isKeepAlive() && e->option->get(PREF_ENABLE_HTTP_PIPELINING) == V_TRUE) {
  109. maxSegments = e->option->getAsInt(PREF_MAX_HTTP_PIPELINING);
  110. } else {
  111. maxSegments = 1;
  112. }
  113. while((int32_t)_segments.size() < maxSegments) {
  114. SegmentHandle segment = _requestGroup->getSegmentMan()->getSegment(cuid);
  115. if(segment.isNull()) {
  116. break;
  117. }
  118. _segments.push_back(segment);
  119. }
  120. if(_segments.empty()) {
  121. logger->info(MSG_NO_SEGMENT_AVAILABLE, cuid);
  122. return prepareForRetry(1);
  123. }
  124. }
  125. return executeInternal();
  126. } else {
  127. if(checkPoint.elapsed(timeout)) {
  128. throw new DlRetryEx(EX_TIME_OUT);
  129. }
  130. e->commands.push_back(this);
  131. return false;
  132. }
  133. } catch(DlAbortEx* err) {
  134. logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str());
  135. onAbort(err);
  136. delete(err);
  137. req->resetUrl();
  138. tryReserved();
  139. return true;
  140. } catch(DlRetryEx* err) {
  141. logger->info(MSG_RESTARTING_DOWNLOAD, err, cuid, req->getUrl().c_str());
  142. req->addTryCount();
  143. bool isAbort = e->option->getAsInt(PREF_MAX_TRIES) != 0 &&
  144. req->getTryCount() >= e->option->getAsInt(PREF_MAX_TRIES);
  145. if(isAbort) {
  146. onAbort(err);
  147. }
  148. if(isAbort) {
  149. logger->info(MSG_MAX_TRY, cuid, req->getTryCount());
  150. logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str());
  151. delete(err);
  152. tryReserved();
  153. return true;
  154. } else {
  155. delete(err);
  156. return prepareForRetry(e->option->getAsInt(PREF_RETRY_WAIT));
  157. }
  158. } catch(FatalException* err) {
  159. delete(err);
  160. _requestGroup->setHaltRequested(true);
  161. return true;
  162. }
  163. }
  164. void AbstractCommand::tryReserved() {
  165. Commands commands = _requestGroup->createNextCommand(e, 1);
  166. e->addCommand(commands);
  167. }
  168. bool AbstractCommand::prepareForRetry(int32_t wait) {
  169. if(!_requestGroup->getPieceStorage().isNull()) {
  170. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  171. }
  172. Command* command = InitiateConnectionCommandFactory::createInitiateConnectionCommand(cuid, req, _requestGroup, e);
  173. if(wait == 0) {
  174. e->commands.push_back(command);
  175. } else {
  176. SleepCommand* scom = new SleepCommand(cuid, e, command, wait);
  177. e->commands.push_back(scom);
  178. }
  179. return true;
  180. }
  181. void AbstractCommand::onAbort(Exception* ex) {
  182. logger->debug(MSG_UNREGISTER_CUID, cuid);
  183. //_segmentMan->unregisterId(cuid);
  184. if(!_requestGroup->getPieceStorage().isNull()) {
  185. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  186. }
  187. }
  188. void AbstractCommand::disableReadCheckSocket() {
  189. if(checkSocketIsReadable) {
  190. e->deleteSocketForReadCheck(readCheckTarget, this);
  191. checkSocketIsReadable = false;
  192. readCheckTarget = SocketHandle();
  193. }
  194. }
  195. void AbstractCommand::setReadCheckSocket(const SocketHandle& socket) {
  196. if(!socket->isOpen()) {
  197. disableReadCheckSocket();
  198. } else {
  199. if(checkSocketIsReadable) {
  200. if(readCheckTarget != socket) {
  201. e->deleteSocketForReadCheck(readCheckTarget, this);
  202. e->addSocketForReadCheck(socket, this);
  203. readCheckTarget = socket;
  204. }
  205. } else {
  206. e->addSocketForReadCheck(socket, this);
  207. checkSocketIsReadable = true;
  208. readCheckTarget = socket;
  209. }
  210. }
  211. }
  212. void AbstractCommand::disableWriteCheckSocket() {
  213. if(checkSocketIsWritable) {
  214. e->deleteSocketForWriteCheck(writeCheckTarget, this);
  215. checkSocketIsWritable = false;
  216. writeCheckTarget = SocketHandle();
  217. }
  218. }
  219. void AbstractCommand::setWriteCheckSocket(const SocketHandle& socket) {
  220. if(!socket->isOpen()) {
  221. disableWriteCheckSocket();
  222. } else {
  223. if(checkSocketIsWritable) {
  224. if(writeCheckTarget != socket) {
  225. e->deleteSocketForWriteCheck(writeCheckTarget, this);
  226. e->addSocketForWriteCheck(socket, this);
  227. writeCheckTarget = socket;
  228. }
  229. } else {
  230. e->addSocketForWriteCheck(socket, this);
  231. checkSocketIsWritable = true;
  232. writeCheckTarget = socket;
  233. }
  234. }
  235. }
  236. bool AbstractCommand::resolveHostname(const string& hostname,
  237. const NameResolverHandle& resolver) {
  238. string ipaddr = DNSCacheSingletonHolder::instance()->find(hostname);
  239. if(ipaddr.empty()) {
  240. #ifdef ENABLE_ASYNC_DNS
  241. switch(resolver->getStatus()) {
  242. case NameResolver::STATUS_READY:
  243. logger->info(MSG_RESOLVING_HOSTNAME, cuid, hostname.c_str());
  244. resolver->resolve(hostname);
  245. setNameResolverCheck(resolver);
  246. return false;
  247. case NameResolver::STATUS_SUCCESS:
  248. logger->info(MSG_NAME_RESOLUTION_COMPLETE, cuid,
  249. hostname.c_str(), resolver->getAddrString().c_str());
  250. DNSCacheSingletonHolder::instance()->put(hostname, resolver->getAddrString());
  251. return true;
  252. break;
  253. case NameResolver::STATUS_ERROR:
  254. throw new DlAbortEx(MSG_NAME_RESOLUTION_FAILED, cuid,
  255. hostname.c_str(),
  256. resolver->getError().c_str());
  257. default:
  258. return false;
  259. }
  260. #else
  261. logger->info(MSG_RESOLVING_HOSTNAME, cuid, hostname.c_str());
  262. resolver->resolve(hostname);
  263. logger->info(MSG_NAME_RESOLUTION_COMPLETE, cuid,
  264. hostname.c_str(), resolver->getAddrString().c_str());
  265. DNSCacheSingletonHolder::instance()->put(hostname, resolver->getAddrString());
  266. return true;
  267. #endif // ENABLE_ASYNC_DNS
  268. } else {
  269. logger->info(MSG_DNS_CACHE_HIT, cuid,
  270. hostname.c_str(), ipaddr.c_str());
  271. resolver->setAddr(ipaddr);
  272. return true;
  273. }
  274. }
  275. #ifdef ENABLE_ASYNC_DNS
  276. void AbstractCommand::setNameResolverCheck(const NameResolverHandle& resolver) {
  277. nameResolverCheck = true;
  278. e->addNameResolverCheck(resolver, this);
  279. }
  280. void AbstractCommand::disableNameResolverCheck(const NameResolverHandle& resolver) {
  281. nameResolverCheck = false;
  282. e->deleteNameResolverCheck(resolver, this);
  283. }
  284. bool AbstractCommand::nameResolveFinished() const {
  285. return false;
  286. }
  287. #endif // ENABLE_ASYNC_DNS
  288. void AbstractCommand::loadAndOpenFile()
  289. {
  290. if(!_requestGroup->isPreLocalFileCheckEnabled()) {
  291. _requestGroup->getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  292. return;
  293. }
  294. //_requestGroup->setProgressInfoFile(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), e->option));
  295. BtProgressInfoFileHandle progressInfoFile =
  296. new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), e->option);
  297. if(progressInfoFile->exists()) {
  298. progressInfoFile->load();
  299. _requestGroup->getPieceStorage()->getDiskAdaptor()->openExistingFile();
  300. } else {
  301. File outfile(_requestGroup->getFilePath());
  302. if(outfile.exists() && e->option->get(PREF_CONTINUE) == V_TRUE) {
  303. if(_requestGroup->getTotalLength() < outfile.size()) {
  304. throw new FatalException(EX_FILE_LENGTH_MISMATCH_BETWEEN_LOCAL_AND_REMOTE,
  305. _requestGroup->getFilePath().c_str(),
  306. Util::llitos(outfile.size()).c_str(),
  307. Util::llitos(_requestGroup->getTotalLength()).c_str());
  308. }
  309. _requestGroup->getPieceStorage()->getDiskAdaptor()->openExistingFile();
  310. _requestGroup->getPieceStorage()->markPiecesDone(outfile.size());
  311. } else {
  312. #ifdef ENABLE_MESSAGE_DIGEST
  313. if(outfile.exists() && e->option->get(PREF_CHECK_INTEGRITY) == V_TRUE) {
  314. _requestGroup->getPieceStorage()->getDiskAdaptor()->openExistingFile();
  315. } else {
  316. shouldCancelDownloadForSafety();
  317. _requestGroup->getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  318. }
  319. #else // ENABLE_MESSAGE_DIGEST
  320. shouldCancelDownloadForSafety();
  321. _requestGroup->getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  322. #endif // ENABLE_MESSAGE_DIGEST
  323. }
  324. }
  325. _requestGroup->setProgressInfoFile(progressInfoFile);
  326. }
  327. void AbstractCommand::shouldCancelDownloadForSafety()
  328. {
  329. File outfile(_requestGroup->getFilePath());
  330. if(outfile.exists() && !_requestGroup->getProgressInfoFile()->exists()) {
  331. if(e->option->get(PREF_AUTO_FILE_RENAMING) == V_TRUE) {
  332. if(tryAutoFileRenaming()) {
  333. logger->notice("File already exists. Renamed to %s.",
  334. _requestGroup->getFilePath().c_str());
  335. } else {
  336. logger->notice("File renaming failed: %s",
  337. _requestGroup->getFilePath().c_str());
  338. throw new FatalException(EX_DOWNLOAD_ABORTED);
  339. }
  340. } else if(e->option->get(PREF_ALLOW_OVERWRITE) != V_TRUE) {
  341. logger->notice(MSG_FILE_ALREADY_EXISTS,
  342. _requestGroup->getFilePath().c_str(),
  343. _requestGroup->getProgressInfoFile()->getFilename().c_str());
  344. throw new FatalException(EX_DOWNLOAD_ABORTED);
  345. }
  346. }
  347. }
  348. bool AbstractCommand::tryAutoFileRenaming()
  349. {
  350. string filepath = _requestGroup->getFilePath();
  351. if(filepath.empty()) {
  352. return false;
  353. }
  354. for(int32_t i = 1; i < 10000; ++i) {
  355. File newfile(filepath+"."+Util::itos(i));
  356. if(!newfile.exists()) {
  357. SingleFileDownloadContextHandle(_requestGroup->getDownloadContext())->setUFilename(newfile.getBasename());
  358. return true;
  359. }
  360. }
  361. return false;
  362. }
  363. void AbstractCommand::initPieceStorage()
  364. {
  365. if(_requestGroup->getDownloadContext()->getTotalLength() == 0) {
  366. UnknownLengthPieceStorageHandle ps = new UnknownLengthPieceStorage(_requestGroup->getDownloadContext(), e->option);
  367. if(!_requestGroup->getDiskWriterFactory().isNull()) {
  368. ps->setDiskWriterFactory(_requestGroup->getDiskWriterFactory());
  369. }
  370. _requestGroup->setPieceStorage(ps);
  371. } else {
  372. DefaultPieceStorageHandle ps = new DefaultPieceStorage(_requestGroup->getDownloadContext(), e->option);
  373. if(!_requestGroup->getDiskWriterFactory().isNull()) {
  374. ps->setDiskWriterFactory(_requestGroup->getDiskWriterFactory());
  375. }
  376. _requestGroup->setPieceStorage(ps);
  377. }
  378. _requestGroup->getPieceStorage()->initStorage();
  379. _requestGroup->initSegmentMan();
  380. }
  381. bool AbstractCommand::downloadFinishedByFileLength()
  382. {
  383. // check existence of control file using ProgressInfoFile class.
  384. if(_requestGroup->getProgressInfoFile()->exists()) {
  385. return false;
  386. }
  387. // TODO consider the case when the getFilePath() returns dir path.
  388. File outfile(_requestGroup->getFilePath());
  389. if(outfile.exists() &&
  390. _requestGroup->getTotalLength() == outfile.size()) {
  391. _requestGroup->getPieceStorage()->markAllPiecesDone();
  392. return true;
  393. } else {
  394. return false;
  395. }
  396. }
  397. void AbstractCommand::prepareForNextAction(Command* nextCommand)
  398. {
  399. CheckIntegrityEntryHandle entry =
  400. new StreamCheckIntegrityEntry(req, _requestGroup, nextCommand);
  401. #ifdef ENABLE_MESSAGE_DIGEST
  402. if(File(_requestGroup->getFilePath()).size() > 0 &&
  403. e->option->get(PREF_CHECK_INTEGRITY) == V_TRUE &&
  404. entry->isValidationReady()) {
  405. entry->initValidator();
  406. logger->debug("Issuing CheckIntegrityCommand.");
  407. CheckIntegrityCommand* command =
  408. new CheckIntegrityCommand(CUIDCounterSingletonHolder::instance()->newID(), _requestGroup, e, entry);
  409. e->commands.push_back(command);
  410. } else
  411. #endif // ENABLE_MESSAGE_DIGEST
  412. {
  413. e->addCommand(entry->prepareForNextAction(e));
  414. }
  415. }