AbstractCommand.cc 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 "RequestGroup.h"
  37. #include "Request.h"
  38. #include "DownloadEngine.h"
  39. #include "Option.h"
  40. #include "PeerStat.h"
  41. #include "SegmentMan.h"
  42. #include "Logger.h"
  43. #include "Segment.h"
  44. #include "DlAbortEx.h"
  45. #include "DlRetryEx.h"
  46. #include "DownloadFailureException.h"
  47. #include "InitiateConnectionCommandFactory.h"
  48. #include "SleepCommand.h"
  49. #ifdef ENABLE_ASYNC_DNS
  50. #include "AsyncNameResolver.h"
  51. #endif // ENABLE_ASYNC_DNS
  52. #include "StreamCheckIntegrityEntry.h"
  53. #include "PieceStorage.h"
  54. #include "Socket.h"
  55. #include "message.h"
  56. #include "prefs.h"
  57. #include "StringFormat.h"
  58. namespace aria2 {
  59. AbstractCommand::AbstractCommand(int32_t cuid,
  60. const SharedHandle<Request>& req,
  61. RequestGroup* requestGroup,
  62. DownloadEngine* e,
  63. const SocketHandle& s):
  64. Command(cuid), RequestGroupAware(requestGroup),
  65. req(req), e(e), socket(s),
  66. checkSocketIsReadable(false), checkSocketIsWritable(false),
  67. nameResolverCheck(false)
  68. {
  69. if(!socket.isNull() && socket->isOpen()) {
  70. setReadCheckSocket(socket);
  71. }
  72. timeout = this->e->option->getAsInt(PREF_TIMEOUT);
  73. _requestGroup->increaseStreamConnection();
  74. }
  75. AbstractCommand::~AbstractCommand() {
  76. disableReadCheckSocket();
  77. disableWriteCheckSocket();
  78. #ifdef ENABLE_ASYNC_DNS
  79. disableNameResolverCheck(_asyncNameResolver);
  80. #endif // ENABLE_ASYNC_DNS
  81. _requestGroup->decreaseStreamConnection();
  82. }
  83. bool AbstractCommand::execute() {
  84. try {
  85. if(_requestGroup->downloadFinished() || _requestGroup->isHaltRequested()) {
  86. //logger->debug("CUID#%d - finished.", cuid);
  87. return true;
  88. }
  89. PeerStatHandle peerStat;
  90. if(!_requestGroup->getSegmentMan().isNull()) {
  91. peerStat = _requestGroup->getSegmentMan()->getPeerStat(cuid);
  92. }
  93. if(!peerStat.isNull()) {
  94. if(peerStat->getStatus() == PeerStat::REQUEST_IDLE) {
  95. logger->info(MSG_ABORT_REQUESTED, cuid);
  96. onAbort();
  97. req->resetUrl();
  98. tryReserved();
  99. return true;
  100. }
  101. }
  102. if((checkSocketIsReadable && _readEvent) ||
  103. (checkSocketIsWritable && _writeEvent) ||
  104. _errorEvent ||
  105. #ifdef ENABLE_ASYNC_DNS
  106. (nameResolverCheck && nameResolveFinished()) ||
  107. #endif // ENABLE_ASYNC_DNS
  108. (!checkSocketIsReadable && !checkSocketIsWritable && !nameResolverCheck)) {
  109. checkPoint.reset();
  110. if(!_requestGroup->getPieceStorage().isNull()) {
  111. _segments.clear();
  112. _requestGroup->getSegmentMan()->getInFlightSegment(_segments, cuid);
  113. size_t maxSegments;
  114. if(req->isPipeliningEnabled()) {
  115. maxSegments = e->option->getAsInt(PREF_MAX_HTTP_PIPELINING);
  116. } else {
  117. maxSegments = 1;
  118. }
  119. while(_segments.size() < maxSegments) {
  120. SegmentHandle segment = _requestGroup->getSegmentMan()->getSegment(cuid);
  121. if(segment.isNull()) {
  122. break;
  123. }
  124. _segments.push_back(segment);
  125. }
  126. if(_segments.empty()) {
  127. // TODO socket could be pooled here if pipelining is enabled...
  128. logger->info(MSG_NO_SEGMENT_AVAILABLE, cuid);
  129. return prepareForRetry(1);
  130. }
  131. }
  132. return executeInternal();
  133. } else {
  134. if(checkPoint.elapsed(timeout)) {
  135. throw DlRetryEx(EX_TIME_OUT);
  136. }
  137. e->commands.push_back(this);
  138. return false;
  139. }
  140. } catch(DlAbortEx& err) {
  141. logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str());
  142. onAbort();
  143. req->resetUrl();
  144. tryReserved();
  145. return true;
  146. } catch(DlRetryEx& err) {
  147. logger->info(MSG_RESTARTING_DOWNLOAD, err, cuid, req->getUrl().c_str());
  148. req->addTryCount();
  149. req->resetRedirectCount();
  150. bool isAbort = e->option->getAsInt(PREF_MAX_TRIES) != 0 &&
  151. req->getTryCount() >= (unsigned int)e->option->getAsInt(PREF_MAX_TRIES);
  152. if(isAbort) {
  153. onAbort();
  154. }
  155. // In case where Request::getCurrentUrl() is not a valid URI.
  156. req->resetUrl();
  157. if(isAbort) {
  158. logger->info(MSG_MAX_TRY, cuid, req->getTryCount());
  159. logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str());
  160. tryReserved();
  161. return true;
  162. } else {
  163. return prepareForRetry(e->option->getAsInt(PREF_RETRY_WAIT));
  164. }
  165. } catch(DownloadFailureException& err) {
  166. logger->error(EX_EXCEPTION_CAUGHT, err);
  167. _requestGroup->setHaltRequested(true);
  168. return true;
  169. }
  170. }
  171. void AbstractCommand::tryReserved() {
  172. _requestGroup->removeServerHost(cuid);
  173. Commands commands;
  174. _requestGroup->createNextCommand(commands, e, 1);
  175. e->addCommand(commands);
  176. }
  177. bool AbstractCommand::prepareForRetry(time_t wait) {
  178. if(!_requestGroup->getPieceStorage().isNull()) {
  179. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  180. }
  181. Command* command = InitiateConnectionCommandFactory::createInitiateConnectionCommand(cuid, req, _requestGroup, e);
  182. if(wait == 0) {
  183. e->setNoWait(true);
  184. e->commands.push_back(command);
  185. } else {
  186. SleepCommand* scom = new SleepCommand(cuid, e, command, wait);
  187. e->commands.push_back(scom);
  188. }
  189. return true;
  190. }
  191. void AbstractCommand::onAbort() {
  192. logger->debug(MSG_UNREGISTER_CUID, cuid);
  193. //_segmentMan->unregisterId(cuid);
  194. if(!_requestGroup->getPieceStorage().isNull()) {
  195. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  196. }
  197. }
  198. void AbstractCommand::disableReadCheckSocket() {
  199. if(checkSocketIsReadable) {
  200. e->deleteSocketForReadCheck(readCheckTarget, this);
  201. checkSocketIsReadable = false;
  202. readCheckTarget = SocketHandle();
  203. }
  204. }
  205. void AbstractCommand::setReadCheckSocket(const SocketHandle& socket) {
  206. if(!socket->isOpen()) {
  207. disableReadCheckSocket();
  208. } else {
  209. if(checkSocketIsReadable) {
  210. if(readCheckTarget != socket) {
  211. e->deleteSocketForReadCheck(readCheckTarget, this);
  212. e->addSocketForReadCheck(socket, this);
  213. readCheckTarget = socket;
  214. }
  215. } else {
  216. e->addSocketForReadCheck(socket, this);
  217. checkSocketIsReadable = true;
  218. readCheckTarget = socket;
  219. }
  220. }
  221. }
  222. void AbstractCommand::disableWriteCheckSocket() {
  223. if(checkSocketIsWritable) {
  224. e->deleteSocketForWriteCheck(writeCheckTarget, this);
  225. checkSocketIsWritable = false;
  226. writeCheckTarget = SocketHandle();
  227. }
  228. }
  229. void AbstractCommand::setWriteCheckSocket(const SocketHandle& socket) {
  230. if(!socket->isOpen()) {
  231. disableWriteCheckSocket();
  232. } else {
  233. if(checkSocketIsWritable) {
  234. if(writeCheckTarget != socket) {
  235. e->deleteSocketForWriteCheck(writeCheckTarget, this);
  236. e->addSocketForWriteCheck(socket, this);
  237. writeCheckTarget = socket;
  238. }
  239. } else {
  240. e->addSocketForWriteCheck(socket, this);
  241. checkSocketIsWritable = true;
  242. writeCheckTarget = socket;
  243. }
  244. }
  245. }
  246. #ifdef ENABLE_ASYNC_DNS
  247. bool AbstractCommand::isAsyncNameResolverInitialized() const
  248. {
  249. return !_asyncNameResolver.isNull();
  250. }
  251. void AbstractCommand::initAsyncNameResolver(const std::string& hostname)
  252. {
  253. _asyncNameResolver.reset(new AsyncNameResolver());
  254. logger->info(MSG_RESOLVING_HOSTNAME, cuid, hostname.c_str());
  255. _asyncNameResolver->resolve(hostname);
  256. setNameResolverCheck(_asyncNameResolver);
  257. }
  258. bool AbstractCommand::asyncResolveHostname()
  259. {
  260. switch(_asyncNameResolver->getStatus()) {
  261. case AsyncNameResolver::STATUS_SUCCESS:
  262. return true;
  263. case AsyncNameResolver::STATUS_ERROR:
  264. throw DlAbortEx(StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid,
  265. _asyncNameResolver->getHostname().c_str(),
  266. _asyncNameResolver->getError().c_str()).str());
  267. default:
  268. return false;
  269. }
  270. }
  271. const std::deque<std::string>& AbstractCommand::getResolvedAddresses()
  272. {
  273. return _asyncNameResolver->getResolvedAddresses();
  274. }
  275. void AbstractCommand::setNameResolverCheck
  276. (const SharedHandle<AsyncNameResolver>& resolver) {
  277. if(!resolver.isNull()) {
  278. nameResolverCheck = true;
  279. e->addNameResolverCheck(resolver, this);
  280. }
  281. }
  282. void AbstractCommand::disableNameResolverCheck
  283. (const SharedHandle<AsyncNameResolver>& resolver) {
  284. if(!resolver.isNull()) {
  285. nameResolverCheck = false;
  286. e->deleteNameResolverCheck(resolver, this);
  287. }
  288. }
  289. bool AbstractCommand::nameResolveFinished() const {
  290. return
  291. _asyncNameResolver->getStatus() == AsyncNameResolver::STATUS_SUCCESS ||
  292. _asyncNameResolver->getStatus() == AsyncNameResolver::STATUS_ERROR;
  293. }
  294. #endif // ENABLE_ASYNC_DNS
  295. void AbstractCommand::prepareForNextAction(Command* nextCommand)
  296. {
  297. CheckIntegrityEntryHandle entry(new StreamCheckIntegrityEntry(req, _requestGroup, nextCommand));
  298. std::deque<Command*> commands;
  299. _requestGroup->processCheckIntegrityEntry(commands, entry, e);
  300. e->addCommand(commands);
  301. e->setNoWait(true);
  302. }
  303. } // namespace aria2