AbstractCommand.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 <algorithm>
  37. #include "RequestGroup.h"
  38. #include "Request.h"
  39. #include "DownloadEngine.h"
  40. #include "Option.h"
  41. #include "PeerStat.h"
  42. #include "SegmentMan.h"
  43. #include "Logger.h"
  44. #include "Segment.h"
  45. #include "DlAbortEx.h"
  46. #include "DlRetryEx.h"
  47. #include "DownloadFailureException.h"
  48. #include "InitiateConnectionCommandFactory.h"
  49. #include "SleepCommand.h"
  50. #ifdef ENABLE_ASYNC_DNS
  51. #include "AsyncNameResolver.h"
  52. #endif // ENABLE_ASYNC_DNS
  53. #include "StreamCheckIntegrityEntry.h"
  54. #include "PieceStorage.h"
  55. #include "Socket.h"
  56. #include "message.h"
  57. #include "prefs.h"
  58. #include "StringFormat.h"
  59. #include "ServerStat.h"
  60. #include "RequestGroupMan.h"
  61. #include "A2STR.h"
  62. #include "Util.h"
  63. namespace aria2 {
  64. AbstractCommand::AbstractCommand(int32_t cuid,
  65. const SharedHandle<Request>& req,
  66. RequestGroup* requestGroup,
  67. DownloadEngine* e,
  68. const SocketHandle& s):
  69. Command(cuid), RequestGroupAware(requestGroup),
  70. req(req), e(e), socket(s),
  71. checkSocketIsReadable(false), checkSocketIsWritable(false),
  72. nameResolverCheck(false)
  73. {
  74. if(!socket.isNull() && socket->isOpen()) {
  75. setReadCheckSocket(socket);
  76. }
  77. timeout = _requestGroup->getTimeout();
  78. _requestGroup->increaseStreamConnection();
  79. }
  80. AbstractCommand::~AbstractCommand() {
  81. disableReadCheckSocket();
  82. disableWriteCheckSocket();
  83. #ifdef ENABLE_ASYNC_DNS
  84. disableNameResolverCheck(_asyncNameResolver);
  85. #endif // ENABLE_ASYNC_DNS
  86. _requestGroup->decreaseStreamConnection();
  87. }
  88. bool AbstractCommand::execute() {
  89. logger->debug("CUID#%d - socket: read:%d, write:%d, hup:%d, err:%d",
  90. cuid, _readEvent, _writeEvent, _hupEvent, _errorEvent);
  91. try {
  92. if(_requestGroup->downloadFinished() || _requestGroup->isHaltRequested()) {
  93. //logger->debug("CUID#%d - finished.", cuid);
  94. return true;
  95. }
  96. PeerStatHandle peerStat;
  97. if(!_requestGroup->getSegmentMan().isNull()) {
  98. peerStat = _requestGroup->getSegmentMan()->getPeerStat(cuid);
  99. }
  100. if(!peerStat.isNull()) {
  101. if(peerStat->getStatus() == PeerStat::REQUEST_IDLE) {
  102. logger->info(MSG_ABORT_REQUESTED, cuid);
  103. onAbort();
  104. req->resetUrl();
  105. tryReserved();
  106. return true;
  107. }
  108. }
  109. if((checkSocketIsReadable && _readEvent) ||
  110. (checkSocketIsWritable && _writeEvent) ||
  111. _hupEvent ||
  112. #ifdef ENABLE_ASYNC_DNS
  113. (nameResolverCheck && nameResolveFinished()) ||
  114. #endif // ENABLE_ASYNC_DNS
  115. (!checkSocketIsReadable && !checkSocketIsWritable && !nameResolverCheck)) {
  116. checkPoint.reset();
  117. if(!_requestGroup->getPieceStorage().isNull()) {
  118. _segments.clear();
  119. _requestGroup->getSegmentMan()->getInFlightSegment(_segments, cuid);
  120. while(_segments.size() < req->getMaxPipelinedRequest()) {
  121. SegmentHandle segment = _requestGroup->getSegmentMan()->getSegment(cuid);
  122. if(segment.isNull()) {
  123. break;
  124. }
  125. _segments.push_back(segment);
  126. }
  127. if(_segments.empty()) {
  128. // TODO socket could be pooled here if pipelining is enabled...
  129. logger->info(MSG_NO_SEGMENT_AVAILABLE, cuid);
  130. return prepareForRetry(1);
  131. }
  132. }
  133. return executeInternal();
  134. } else if(_errorEvent) {
  135. throw DlRetryEx
  136. (StringFormat(MSG_NETWORK_PROBLEM,
  137. socket->getSocketError().c_str()).str());
  138. } else {
  139. if(checkPoint.elapsed(timeout)) {
  140. // timeout triggers ServerStat error state.
  141. SharedHandle<ServerStat> ss =
  142. e->_requestGroupMan->getOrCreateServerStat(req->getHost(),
  143. req->getProtocol());
  144. ss->setError();
  145. throw DlRetryEx(EX_TIME_OUT, DownloadResult::TIME_OUT);
  146. }
  147. e->commands.push_back(this);
  148. return false;
  149. }
  150. } catch(DlAbortEx& err) {
  151. logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str());
  152. _requestGroup->addURIResult(req->getUrl(), err.getCode());
  153. onAbort();
  154. req->resetUrl();
  155. tryReserved();
  156. return true;
  157. } catch(DlRetryEx& err) {
  158. logger->info(MSG_RESTARTING_DOWNLOAD, err, cuid, req->getUrl().c_str());
  159. req->addTryCount();
  160. req->resetRedirectCount();
  161. bool isAbort = _requestGroup->getMaxTries() != 0 &&
  162. req->getTryCount() >= _requestGroup->getMaxTries();
  163. if(isAbort) {
  164. onAbort();
  165. req->resetUrl();
  166. } else {
  167. if(e->option->getAsBool(PREF_RESET_URI)) {
  168. req->resetUrl();
  169. }
  170. }
  171. if(isAbort) {
  172. logger->info(MSG_MAX_TRY, cuid, req->getTryCount());
  173. logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str());
  174. _requestGroup->addURIResult(req->getUrl(), err.getCode());
  175. tryReserved();
  176. return true;
  177. } else {
  178. return prepareForRetry(e->option->getAsInt(PREF_RETRY_WAIT));
  179. }
  180. } catch(DownloadFailureException& err) {
  181. logger->error(EX_EXCEPTION_CAUGHT, err);
  182. _requestGroup->addURIResult(req->getUrl(), err.getCode());
  183. _requestGroup->setHaltRequested(true);
  184. return true;
  185. }
  186. }
  187. void AbstractCommand::tryReserved() {
  188. _requestGroup->removeServerHost(cuid);
  189. Commands commands;
  190. _requestGroup->createNextCommand(commands, e, 1);
  191. e->setNoWait(true);
  192. e->addCommand(commands);
  193. }
  194. bool AbstractCommand::prepareForRetry(time_t wait) {
  195. if(!_requestGroup->getPieceStorage().isNull()) {
  196. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  197. }
  198. Command* command = InitiateConnectionCommandFactory::createInitiateConnectionCommand(cuid, req, _requestGroup, e);
  199. if(wait == 0) {
  200. e->setNoWait(true);
  201. e->commands.push_back(command);
  202. } else {
  203. SleepCommand* scom = new SleepCommand(cuid, e, _requestGroup,
  204. command, wait);
  205. e->commands.push_back(scom);
  206. }
  207. return true;
  208. }
  209. void AbstractCommand::onAbort() {
  210. // TODO This might be a problem if the failure is caused by proxy.
  211. e->_requestGroupMan->getOrCreateServerStat(req->getHost(),
  212. req->getProtocol())->setError();
  213. logger->debug(MSG_UNREGISTER_CUID, cuid);
  214. //_segmentMan->unregisterId(cuid);
  215. if(!_requestGroup->getPieceStorage().isNull()) {
  216. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  217. }
  218. _requestGroup->removeIdenticalURI(req->getUrl());
  219. }
  220. void AbstractCommand::disableReadCheckSocket() {
  221. if(checkSocketIsReadable) {
  222. e->deleteSocketForReadCheck(readCheckTarget, this);
  223. checkSocketIsReadable = false;
  224. readCheckTarget = SocketHandle();
  225. }
  226. }
  227. void AbstractCommand::setReadCheckSocket(const SocketHandle& socket) {
  228. if(!socket->isOpen()) {
  229. disableReadCheckSocket();
  230. } else {
  231. if(checkSocketIsReadable) {
  232. if(readCheckTarget != socket) {
  233. e->deleteSocketForReadCheck(readCheckTarget, this);
  234. e->addSocketForReadCheck(socket, this);
  235. readCheckTarget = socket;
  236. }
  237. } else {
  238. e->addSocketForReadCheck(socket, this);
  239. checkSocketIsReadable = true;
  240. readCheckTarget = socket;
  241. }
  242. }
  243. }
  244. void AbstractCommand::setReadCheckSocketIf
  245. (const SharedHandle<SocketCore>& socket, bool pred)
  246. {
  247. if(pred) {
  248. setReadCheckSocket(socket);
  249. } else {
  250. disableReadCheckSocket();
  251. }
  252. }
  253. void AbstractCommand::disableWriteCheckSocket() {
  254. if(checkSocketIsWritable) {
  255. e->deleteSocketForWriteCheck(writeCheckTarget, this);
  256. checkSocketIsWritable = false;
  257. writeCheckTarget = SocketHandle();
  258. }
  259. }
  260. void AbstractCommand::setWriteCheckSocket(const SocketHandle& socket) {
  261. if(!socket->isOpen()) {
  262. disableWriteCheckSocket();
  263. } else {
  264. if(checkSocketIsWritable) {
  265. if(writeCheckTarget != socket) {
  266. e->deleteSocketForWriteCheck(writeCheckTarget, this);
  267. e->addSocketForWriteCheck(socket, this);
  268. writeCheckTarget = socket;
  269. }
  270. } else {
  271. e->addSocketForWriteCheck(socket, this);
  272. checkSocketIsWritable = true;
  273. writeCheckTarget = socket;
  274. }
  275. }
  276. }
  277. void AbstractCommand::setWriteCheckSocketIf
  278. (const SharedHandle<SocketCore>& socket, bool pred)
  279. {
  280. if(pred) {
  281. setWriteCheckSocket(socket);
  282. } else {
  283. disableWriteCheckSocket();
  284. }
  285. }
  286. static const std::string& getProxyStringFor(const std::string& proxyPref,
  287. const Option* option)
  288. {
  289. if(option->defined(proxyPref)) {
  290. return option->get(proxyPref);
  291. } else {
  292. return option->get(PREF_ALL_PROXY);
  293. }
  294. }
  295. static bool isProxyUsed(const std::string& proxyPref,
  296. const Option* option)
  297. {
  298. std::string proxy = getProxyStringFor(proxyPref, option);
  299. if(proxy.empty()) {
  300. return false;
  301. } else {
  302. return Request().setUrl(proxy);
  303. }
  304. }
  305. static bool isProxyRequest(const std::string& protocol, const Option* option)
  306. {
  307. return
  308. (protocol == Request::PROTO_HTTP && isProxyUsed(PREF_HTTP_PROXY, option)) ||
  309. (protocol == Request::PROTO_HTTPS && isProxyUsed(PREF_HTTPS_PROXY,option))||
  310. (protocol == Request::PROTO_FTP && isProxyUsed(PREF_FTP_PROXY, option));
  311. }
  312. class DomainMatch {
  313. private:
  314. std::string _hostname;
  315. public:
  316. DomainMatch(const std::string& hostname):_hostname(hostname) {}
  317. bool operator()(const std::string& domain) const
  318. {
  319. if(Util::startsWith(domain, ".")) {
  320. return Util::endsWith(_hostname, domain);
  321. } else {
  322. return Util::endsWith(_hostname, "."+domain);
  323. }
  324. }
  325. };
  326. static bool inNoProxy(const SharedHandle<Request>& req,
  327. const std::string& noProxy)
  328. {
  329. std::deque<std::string> entries;
  330. Util::slice(entries, noProxy, ',', true);
  331. if(entries.empty()) {
  332. return false;
  333. }
  334. return
  335. std::find_if(entries.begin(), entries.end(),
  336. DomainMatch("."+req->getHost())) != entries.end();
  337. }
  338. bool AbstractCommand::isProxyDefined() const
  339. {
  340. return isProxyRequest(req->getProtocol(), e->option) &&
  341. !inNoProxy(req, e->option->get(PREF_NO_PROXY));
  342. }
  343. static const std::string& getProxyString(const SharedHandle<Request>& req,
  344. const Option* option)
  345. {
  346. if(req->getProtocol() == Request::PROTO_HTTP) {
  347. return getProxyStringFor(PREF_HTTP_PROXY, option);
  348. } else if(req->getProtocol() == Request::PROTO_HTTPS) {
  349. return getProxyStringFor(PREF_HTTPS_PROXY, option);
  350. } else if(req->getProtocol() == Request::PROTO_FTP) {
  351. return getProxyStringFor(PREF_FTP_PROXY, option);
  352. } else {
  353. return A2STR::NIL;
  354. }
  355. }
  356. SharedHandle<Request> AbstractCommand::createProxyRequest() const
  357. {
  358. SharedHandle<Request> proxyRequest;
  359. if(inNoProxy(req, e->option->get(PREF_NO_PROXY))) {
  360. return proxyRequest;
  361. }
  362. std::string proxy = getProxyString(req, e->option);
  363. if(!proxy.empty()) {
  364. proxyRequest.reset(new Request());
  365. if(proxyRequest->setUrl(proxy)) {
  366. logger->debug("CUID#%d - Using proxy", cuid);
  367. } else {
  368. logger->debug("CUID#%d - Failed to parse proxy string", cuid);
  369. proxyRequest.reset();
  370. }
  371. }
  372. return proxyRequest;
  373. }
  374. #ifdef ENABLE_ASYNC_DNS
  375. bool AbstractCommand::isAsyncNameResolverInitialized() const
  376. {
  377. return !_asyncNameResolver.isNull();
  378. }
  379. void AbstractCommand::initAsyncNameResolver(const std::string& hostname)
  380. {
  381. _asyncNameResolver.reset(new AsyncNameResolver());
  382. logger->info(MSG_RESOLVING_HOSTNAME, cuid, hostname.c_str());
  383. _asyncNameResolver->resolve(hostname);
  384. setNameResolverCheck(_asyncNameResolver);
  385. }
  386. bool AbstractCommand::asyncResolveHostname()
  387. {
  388. switch(_asyncNameResolver->getStatus()) {
  389. case AsyncNameResolver::STATUS_SUCCESS:
  390. return true;
  391. case AsyncNameResolver::STATUS_ERROR:
  392. if(!isProxyRequest(req->getProtocol(), e->option)) {
  393. e->_requestGroupMan->getOrCreateServerStat
  394. (req->getHost(), req->getProtocol())->setError();
  395. }
  396. throw DlAbortEx(StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid,
  397. _asyncNameResolver->getHostname().c_str(),
  398. _asyncNameResolver->getError().c_str()).str());
  399. default:
  400. return false;
  401. }
  402. }
  403. const std::deque<std::string>& AbstractCommand::getResolvedAddresses()
  404. {
  405. return _asyncNameResolver->getResolvedAddresses();
  406. }
  407. void AbstractCommand::setNameResolverCheck
  408. (const SharedHandle<AsyncNameResolver>& resolver) {
  409. if(!resolver.isNull()) {
  410. nameResolverCheck = true;
  411. e->addNameResolverCheck(resolver, this);
  412. }
  413. }
  414. void AbstractCommand::disableNameResolverCheck
  415. (const SharedHandle<AsyncNameResolver>& resolver) {
  416. if(!resolver.isNull()) {
  417. nameResolverCheck = false;
  418. e->deleteNameResolverCheck(resolver, this);
  419. }
  420. }
  421. bool AbstractCommand::nameResolveFinished() const {
  422. return
  423. _asyncNameResolver->getStatus() == AsyncNameResolver::STATUS_SUCCESS ||
  424. _asyncNameResolver->getStatus() == AsyncNameResolver::STATUS_ERROR;
  425. }
  426. #endif // ENABLE_ASYNC_DNS
  427. void AbstractCommand::prepareForNextAction(Command* nextCommand)
  428. {
  429. CheckIntegrityEntryHandle entry(new StreamCheckIntegrityEntry(req, _requestGroup, nextCommand));
  430. std::deque<Command*> commands;
  431. _requestGroup->processCheckIntegrityEntry(commands, entry, e);
  432. e->addCommand(commands);
  433. e->setNoWait(true);
  434. }
  435. void AbstractCommand::checkIfConnectionEstablished
  436. (const SharedHandle<SocketCore>& socket)
  437. {
  438. if(socket->isReadable(0)) {
  439. std::string error = socket->getSocketError();
  440. if(!error.empty()) {
  441. // Don't set error if proxy server is used and its method is GET.
  442. if(resolveProxyMethod(req->getProtocol()) != V_GET ||
  443. !isProxyRequest(req->getProtocol(), e->option)) {
  444. e->_requestGroupMan->getOrCreateServerStat
  445. (req->getHost(), req->getProtocol())->setError();
  446. }
  447. throw DlRetryEx
  448. (StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()).str());
  449. }
  450. }
  451. }
  452. const std::string& AbstractCommand::resolveProxyMethod
  453. (const std::string& protocol) const
  454. {
  455. if(e->option->get(PREF_PROXY_METHOD) == V_TUNNEL ||
  456. Request::PROTO_HTTPS == protocol) {
  457. return V_TUNNEL;
  458. } else {
  459. return V_GET;
  460. }
  461. }
  462. } // namespace aria2