AbstractCommand.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. #include "ServerStat.h"
  59. #include "RequestGroupMan.h"
  60. namespace aria2 {
  61. AbstractCommand::AbstractCommand(int32_t cuid,
  62. const SharedHandle<Request>& req,
  63. RequestGroup* requestGroup,
  64. DownloadEngine* e,
  65. const SocketHandle& s):
  66. Command(cuid), RequestGroupAware(requestGroup),
  67. req(req), e(e), socket(s),
  68. checkSocketIsReadable(false), checkSocketIsWritable(false),
  69. nameResolverCheck(false)
  70. {
  71. if(!socket.isNull() && socket->isOpen()) {
  72. setReadCheckSocket(socket);
  73. }
  74. timeout = this->e->option->getAsInt(PREF_TIMEOUT);
  75. _requestGroup->increaseStreamConnection();
  76. }
  77. AbstractCommand::~AbstractCommand() {
  78. disableReadCheckSocket();
  79. disableWriteCheckSocket();
  80. #ifdef ENABLE_ASYNC_DNS
  81. disableNameResolverCheck(_asyncNameResolver);
  82. #endif // ENABLE_ASYNC_DNS
  83. _requestGroup->decreaseStreamConnection();
  84. }
  85. bool AbstractCommand::execute() {
  86. logger->debug("CUID#%d - socket: read:%d, write:%d, hup:%d, err:%d",
  87. cuid, _readEvent, _writeEvent, _hupEvent, _errorEvent);
  88. try {
  89. if(_requestGroup->downloadFinished() || _requestGroup->isHaltRequested()) {
  90. //logger->debug("CUID#%d - finished.", cuid);
  91. return true;
  92. }
  93. PeerStatHandle peerStat;
  94. if(!_requestGroup->getSegmentMan().isNull()) {
  95. peerStat = _requestGroup->getSegmentMan()->getPeerStat(cuid);
  96. }
  97. if(!peerStat.isNull()) {
  98. if(peerStat->getStatus() == PeerStat::REQUEST_IDLE) {
  99. logger->info(MSG_ABORT_REQUESTED, cuid);
  100. onAbort();
  101. req->resetUrl();
  102. tryReserved();
  103. return true;
  104. }
  105. }
  106. if((checkSocketIsReadable && _readEvent) ||
  107. (checkSocketIsWritable && _writeEvent) ||
  108. _hupEvent ||
  109. #ifdef ENABLE_ASYNC_DNS
  110. (nameResolverCheck && nameResolveFinished()) ||
  111. #endif // ENABLE_ASYNC_DNS
  112. (!checkSocketIsReadable && !checkSocketIsWritable && !nameResolverCheck)) {
  113. checkPoint.reset();
  114. if(!_requestGroup->getPieceStorage().isNull()) {
  115. _segments.clear();
  116. _requestGroup->getSegmentMan()->getInFlightSegment(_segments, cuid);
  117. size_t maxSegments;
  118. if(req->isPipeliningEnabled()) {
  119. maxSegments = e->option->getAsInt(PREF_MAX_HTTP_PIPELINING);
  120. } else {
  121. maxSegments = 1;
  122. }
  123. while(_segments.size() < maxSegments) {
  124. SegmentHandle segment = _requestGroup->getSegmentMan()->getSegment(cuid);
  125. if(segment.isNull()) {
  126. break;
  127. }
  128. _segments.push_back(segment);
  129. }
  130. if(_segments.empty()) {
  131. // TODO socket could be pooled here if pipelining is enabled...
  132. logger->info(MSG_NO_SEGMENT_AVAILABLE, cuid);
  133. return prepareForRetry(1);
  134. }
  135. }
  136. return executeInternal();
  137. } else if(_errorEvent) {
  138. throw DlRetryEx
  139. (StringFormat(MSG_NETWORK_PROBLEM,
  140. socket->getSocketError().c_str()).str());
  141. } else {
  142. if(checkPoint.elapsed(timeout)) {
  143. // timeout triggers ServerStat error state.
  144. SharedHandle<ServerStat> ss =
  145. e->_requestGroupMan->getOrCreateServerStat(req->getHost(),
  146. req->getProtocol());
  147. ss->setError();
  148. throw DlRetryEx(EX_TIME_OUT);
  149. }
  150. e->commands.push_back(this);
  151. return false;
  152. }
  153. } catch(DlAbortEx& err) {
  154. logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str());
  155. onAbort();
  156. req->resetUrl();
  157. tryReserved();
  158. return true;
  159. } catch(DlRetryEx& err) {
  160. logger->info(MSG_RESTARTING_DOWNLOAD, err, cuid, req->getUrl().c_str());
  161. req->addTryCount();
  162. req->resetRedirectCount();
  163. bool isAbort = e->option->getAsInt(PREF_MAX_TRIES) != 0 &&
  164. req->getTryCount() >= (unsigned int)e->option->getAsInt(PREF_MAX_TRIES);
  165. if(isAbort) {
  166. onAbort();
  167. }
  168. // In case where Request::getCurrentUrl() is not a valid URI.
  169. req->resetUrl();
  170. if(isAbort) {
  171. logger->info(MSG_MAX_TRY, cuid, req->getTryCount());
  172. logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str());
  173. tryReserved();
  174. return true;
  175. } else {
  176. return prepareForRetry(e->option->getAsInt(PREF_RETRY_WAIT));
  177. }
  178. } catch(DownloadFailureException& err) {
  179. logger->error(EX_EXCEPTION_CAUGHT, err);
  180. _requestGroup->setHaltRequested(true);
  181. return true;
  182. }
  183. }
  184. void AbstractCommand::tryReserved() {
  185. _requestGroup->removeServerHost(cuid);
  186. Commands commands;
  187. _requestGroup->createNextCommand(commands, e, 1);
  188. e->setNoWait(true);
  189. e->addCommand(commands);
  190. }
  191. bool AbstractCommand::prepareForRetry(time_t wait) {
  192. if(!_requestGroup->getPieceStorage().isNull()) {
  193. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  194. }
  195. Command* command = InitiateConnectionCommandFactory::createInitiateConnectionCommand(cuid, req, _requestGroup, e);
  196. if(wait == 0) {
  197. e->setNoWait(true);
  198. e->commands.push_back(command);
  199. } else {
  200. SleepCommand* scom = new SleepCommand(cuid, e, command, wait);
  201. e->commands.push_back(scom);
  202. }
  203. return true;
  204. }
  205. void AbstractCommand::onAbort() {
  206. logger->debug(MSG_UNREGISTER_CUID, cuid);
  207. //_segmentMan->unregisterId(cuid);
  208. if(!_requestGroup->getPieceStorage().isNull()) {
  209. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  210. }
  211. _requestGroup->removeIdenticalURI(req->getUrl());
  212. }
  213. void AbstractCommand::disableReadCheckSocket() {
  214. if(checkSocketIsReadable) {
  215. e->deleteSocketForReadCheck(readCheckTarget, this);
  216. checkSocketIsReadable = false;
  217. readCheckTarget = SocketHandle();
  218. }
  219. }
  220. void AbstractCommand::setReadCheckSocket(const SocketHandle& socket) {
  221. if(!socket->isOpen()) {
  222. disableReadCheckSocket();
  223. } else {
  224. if(checkSocketIsReadable) {
  225. if(readCheckTarget != socket) {
  226. e->deleteSocketForReadCheck(readCheckTarget, this);
  227. e->addSocketForReadCheck(socket, this);
  228. readCheckTarget = socket;
  229. }
  230. } else {
  231. e->addSocketForReadCheck(socket, this);
  232. checkSocketIsReadable = true;
  233. readCheckTarget = socket;
  234. }
  235. }
  236. }
  237. void AbstractCommand::disableWriteCheckSocket() {
  238. if(checkSocketIsWritable) {
  239. e->deleteSocketForWriteCheck(writeCheckTarget, this);
  240. checkSocketIsWritable = false;
  241. writeCheckTarget = SocketHandle();
  242. }
  243. }
  244. void AbstractCommand::setWriteCheckSocket(const SocketHandle& socket) {
  245. if(!socket->isOpen()) {
  246. disableWriteCheckSocket();
  247. } else {
  248. if(checkSocketIsWritable) {
  249. if(writeCheckTarget != socket) {
  250. e->deleteSocketForWriteCheck(writeCheckTarget, this);
  251. e->addSocketForWriteCheck(socket, this);
  252. writeCheckTarget = socket;
  253. }
  254. } else {
  255. e->addSocketForWriteCheck(socket, this);
  256. checkSocketIsWritable = true;
  257. writeCheckTarget = socket;
  258. }
  259. }
  260. }
  261. static bool isProxyGETRequest(const std::string& protocol, const Option* option)
  262. {
  263. return
  264. // For HTTP/HTTPS
  265. ((protocol == Request::PROTO_HTTP || protocol == Request::PROTO_HTTPS) &&
  266. (option->getAsBool(PREF_HTTP_PROXY_ENABLED) &&
  267. option->get(PREF_HTTP_PROXY_METHOD) == V_GET)) ||
  268. // For FTP
  269. (protocol == Request::PROTO_FTP &&
  270. (option->getAsBool(PREF_HTTP_PROXY_ENABLED) &&
  271. option->get(PREF_FTP_VIA_HTTP_PROXY) == V_GET));
  272. }
  273. #ifdef ENABLE_ASYNC_DNS
  274. bool AbstractCommand::isAsyncNameResolverInitialized() const
  275. {
  276. return !_asyncNameResolver.isNull();
  277. }
  278. void AbstractCommand::initAsyncNameResolver(const std::string& hostname)
  279. {
  280. _asyncNameResolver.reset(new AsyncNameResolver());
  281. logger->info(MSG_RESOLVING_HOSTNAME, cuid, hostname.c_str());
  282. _asyncNameResolver->resolve(hostname);
  283. setNameResolverCheck(_asyncNameResolver);
  284. }
  285. bool AbstractCommand::asyncResolveHostname()
  286. {
  287. switch(_asyncNameResolver->getStatus()) {
  288. case AsyncNameResolver::STATUS_SUCCESS:
  289. return true;
  290. case AsyncNameResolver::STATUS_ERROR:
  291. if(!isProxyGETRequest(req->getProtocol(), e->option)) {
  292. e->_requestGroupMan->getOrCreateServerStat
  293. (req->getHost(), req->getProtocol())->setError();
  294. }
  295. throw DlAbortEx(StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid,
  296. _asyncNameResolver->getHostname().c_str(),
  297. _asyncNameResolver->getError().c_str()).str());
  298. default:
  299. return false;
  300. }
  301. }
  302. const std::deque<std::string>& AbstractCommand::getResolvedAddresses()
  303. {
  304. return _asyncNameResolver->getResolvedAddresses();
  305. }
  306. void AbstractCommand::setNameResolverCheck
  307. (const SharedHandle<AsyncNameResolver>& resolver) {
  308. if(!resolver.isNull()) {
  309. nameResolverCheck = true;
  310. e->addNameResolverCheck(resolver, this);
  311. }
  312. }
  313. void AbstractCommand::disableNameResolverCheck
  314. (const SharedHandle<AsyncNameResolver>& resolver) {
  315. if(!resolver.isNull()) {
  316. nameResolverCheck = false;
  317. e->deleteNameResolverCheck(resolver, this);
  318. }
  319. }
  320. bool AbstractCommand::nameResolveFinished() const {
  321. return
  322. _asyncNameResolver->getStatus() == AsyncNameResolver::STATUS_SUCCESS ||
  323. _asyncNameResolver->getStatus() == AsyncNameResolver::STATUS_ERROR;
  324. }
  325. #endif // ENABLE_ASYNC_DNS
  326. void AbstractCommand::prepareForNextAction(Command* nextCommand)
  327. {
  328. CheckIntegrityEntryHandle entry(new StreamCheckIntegrityEntry(req, _requestGroup, nextCommand));
  329. std::deque<Command*> commands;
  330. _requestGroup->processCheckIntegrityEntry(commands, entry, e);
  331. e->addCommand(commands);
  332. e->setNoWait(true);
  333. }
  334. void AbstractCommand::checkIfConnectionEstablished
  335. (const SharedHandle<SocketCore>& socket)
  336. {
  337. if(socket->isReadable(0)) {
  338. std::string error = socket->getSocketError();
  339. if(!error.empty()) {
  340. // Don't set error if proxy server is used and its method is GET.
  341. if(!isProxyGETRequest(req->getProtocol(), e->option)) {
  342. e->_requestGroupMan->getOrCreateServerStat
  343. (req->getHost(), req->getProtocol())->setError();
  344. }
  345. throw DlRetryEx
  346. (StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()).str());
  347. }
  348. }
  349. }
  350. } // namespace aria2