AbstractCommand.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. }
  166. // In case where Request::getCurrentUrl() is not a valid URI.
  167. req->resetUrl();
  168. if(isAbort) {
  169. logger->info(MSG_MAX_TRY, cuid, req->getTryCount());
  170. logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str());
  171. _requestGroup->addURIResult(req->getUrl(), err.getCode());
  172. tryReserved();
  173. return true;
  174. } else {
  175. return prepareForRetry(e->option->getAsInt(PREF_RETRY_WAIT));
  176. }
  177. } catch(DownloadFailureException& err) {
  178. logger->error(EX_EXCEPTION_CAUGHT, err);
  179. _requestGroup->addURIResult(req->getUrl(), err.getCode());
  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, _requestGroup,
  201. command, wait);
  202. e->commands.push_back(scom);
  203. }
  204. return true;
  205. }
  206. void AbstractCommand::onAbort() {
  207. logger->debug(MSG_UNREGISTER_CUID, cuid);
  208. //_segmentMan->unregisterId(cuid);
  209. if(!_requestGroup->getPieceStorage().isNull()) {
  210. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  211. }
  212. _requestGroup->removeIdenticalURI(req->getUrl());
  213. }
  214. void AbstractCommand::disableReadCheckSocket() {
  215. if(checkSocketIsReadable) {
  216. e->deleteSocketForReadCheck(readCheckTarget, this);
  217. checkSocketIsReadable = false;
  218. readCheckTarget = SocketHandle();
  219. }
  220. }
  221. void AbstractCommand::setReadCheckSocket(const SocketHandle& socket) {
  222. if(!socket->isOpen()) {
  223. disableReadCheckSocket();
  224. } else {
  225. if(checkSocketIsReadable) {
  226. if(readCheckTarget != socket) {
  227. e->deleteSocketForReadCheck(readCheckTarget, this);
  228. e->addSocketForReadCheck(socket, this);
  229. readCheckTarget = socket;
  230. }
  231. } else {
  232. e->addSocketForReadCheck(socket, this);
  233. checkSocketIsReadable = true;
  234. readCheckTarget = socket;
  235. }
  236. }
  237. }
  238. void AbstractCommand::setReadCheckSocketIf
  239. (const SharedHandle<SocketCore>& socket, bool pred)
  240. {
  241. if(pred) {
  242. setReadCheckSocket(socket);
  243. } else {
  244. disableReadCheckSocket();
  245. }
  246. }
  247. void AbstractCommand::disableWriteCheckSocket() {
  248. if(checkSocketIsWritable) {
  249. e->deleteSocketForWriteCheck(writeCheckTarget, this);
  250. checkSocketIsWritable = false;
  251. writeCheckTarget = SocketHandle();
  252. }
  253. }
  254. void AbstractCommand::setWriteCheckSocket(const SocketHandle& socket) {
  255. if(!socket->isOpen()) {
  256. disableWriteCheckSocket();
  257. } else {
  258. if(checkSocketIsWritable) {
  259. if(writeCheckTarget != socket) {
  260. e->deleteSocketForWriteCheck(writeCheckTarget, this);
  261. e->addSocketForWriteCheck(socket, this);
  262. writeCheckTarget = socket;
  263. }
  264. } else {
  265. e->addSocketForWriteCheck(socket, this);
  266. checkSocketIsWritable = true;
  267. writeCheckTarget = socket;
  268. }
  269. }
  270. }
  271. void AbstractCommand::setWriteCheckSocketIf
  272. (const SharedHandle<SocketCore>& socket, bool pred)
  273. {
  274. if(pred) {
  275. setWriteCheckSocket(socket);
  276. } else {
  277. disableWriteCheckSocket();
  278. }
  279. }
  280. static const std::string& getProxyStringFor(const std::string& proxyPref,
  281. const Option* option)
  282. {
  283. if(option->defined(proxyPref)) {
  284. return option->get(proxyPref);
  285. } else {
  286. return option->get(PREF_ALL_PROXY);
  287. }
  288. }
  289. static bool isProxyUsed(const std::string& proxyPref,
  290. const Option* option)
  291. {
  292. std::string proxy = getProxyStringFor(proxyPref, option);
  293. if(proxy.empty()) {
  294. return false;
  295. } else {
  296. return Request().setUrl(proxy);
  297. }
  298. }
  299. static bool isProxyRequest(const std::string& protocol, const Option* option)
  300. {
  301. return
  302. (protocol == Request::PROTO_HTTP && isProxyUsed(PREF_HTTP_PROXY, option)) ||
  303. (protocol == Request::PROTO_HTTPS && isProxyUsed(PREF_HTTPS_PROXY,option))||
  304. (protocol == Request::PROTO_FTP && isProxyUsed(PREF_FTP_PROXY, option));
  305. }
  306. class DomainMatch {
  307. private:
  308. std::string _hostname;
  309. public:
  310. DomainMatch(const std::string& hostname):_hostname(hostname) {}
  311. bool operator()(const std::string& domain) const
  312. {
  313. if(Util::startsWith(domain, ".")) {
  314. return Util::endsWith(_hostname, domain);
  315. } else {
  316. return Util::endsWith(_hostname, "."+domain);
  317. }
  318. }
  319. };
  320. static bool inNoProxy(const SharedHandle<Request>& req,
  321. const std::string& noProxy)
  322. {
  323. std::deque<std::string> entries;
  324. Util::slice(entries, noProxy, ',', true);
  325. if(entries.empty()) {
  326. return false;
  327. }
  328. return
  329. std::find_if(entries.begin(), entries.end(),
  330. DomainMatch("."+req->getHost())) != entries.end();
  331. }
  332. bool AbstractCommand::isProxyDefined() const
  333. {
  334. return isProxyRequest(req->getProtocol(), e->option) &&
  335. !inNoProxy(req, e->option->get(PREF_NO_PROXY));
  336. }
  337. static const std::string& getProxyString(const SharedHandle<Request>& req,
  338. const Option* option)
  339. {
  340. if(req->getProtocol() == Request::PROTO_HTTP) {
  341. return getProxyStringFor(PREF_HTTP_PROXY, option);
  342. } else if(req->getProtocol() == Request::PROTO_HTTPS) {
  343. return getProxyStringFor(PREF_HTTPS_PROXY, option);
  344. } else if(req->getProtocol() == Request::PROTO_FTP) {
  345. return getProxyStringFor(PREF_FTP_PROXY, option);
  346. } else {
  347. return A2STR::NIL;
  348. }
  349. }
  350. SharedHandle<Request> AbstractCommand::createProxyRequest() const
  351. {
  352. SharedHandle<Request> proxyRequest;
  353. if(inNoProxy(req, e->option->get(PREF_NO_PROXY))) {
  354. return proxyRequest;
  355. }
  356. std::string proxy = getProxyString(req, e->option);
  357. if(!proxy.empty()) {
  358. proxyRequest.reset(new Request());
  359. if(proxyRequest->setUrl(proxy)) {
  360. logger->debug("CUID#%d - Using proxy", cuid);
  361. } else {
  362. logger->debug("CUID#%d - Failed to parse proxy string", cuid);
  363. proxyRequest.reset();
  364. }
  365. }
  366. return proxyRequest;
  367. }
  368. #ifdef ENABLE_ASYNC_DNS
  369. bool AbstractCommand::isAsyncNameResolverInitialized() const
  370. {
  371. return !_asyncNameResolver.isNull();
  372. }
  373. void AbstractCommand::initAsyncNameResolver(const std::string& hostname)
  374. {
  375. _asyncNameResolver.reset(new AsyncNameResolver());
  376. logger->info(MSG_RESOLVING_HOSTNAME, cuid, hostname.c_str());
  377. _asyncNameResolver->resolve(hostname);
  378. setNameResolverCheck(_asyncNameResolver);
  379. }
  380. bool AbstractCommand::asyncResolveHostname()
  381. {
  382. switch(_asyncNameResolver->getStatus()) {
  383. case AsyncNameResolver::STATUS_SUCCESS:
  384. return true;
  385. case AsyncNameResolver::STATUS_ERROR:
  386. if(!isProxyRequest(req->getProtocol(), e->option)) {
  387. e->_requestGroupMan->getOrCreateServerStat
  388. (req->getHost(), req->getProtocol())->setError();
  389. }
  390. throw DlAbortEx(StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid,
  391. _asyncNameResolver->getHostname().c_str(),
  392. _asyncNameResolver->getError().c_str()).str());
  393. default:
  394. return false;
  395. }
  396. }
  397. const std::deque<std::string>& AbstractCommand::getResolvedAddresses()
  398. {
  399. return _asyncNameResolver->getResolvedAddresses();
  400. }
  401. void AbstractCommand::setNameResolverCheck
  402. (const SharedHandle<AsyncNameResolver>& resolver) {
  403. if(!resolver.isNull()) {
  404. nameResolverCheck = true;
  405. e->addNameResolverCheck(resolver, this);
  406. }
  407. }
  408. void AbstractCommand::disableNameResolverCheck
  409. (const SharedHandle<AsyncNameResolver>& resolver) {
  410. if(!resolver.isNull()) {
  411. nameResolverCheck = false;
  412. e->deleteNameResolverCheck(resolver, this);
  413. }
  414. }
  415. bool AbstractCommand::nameResolveFinished() const {
  416. return
  417. _asyncNameResolver->getStatus() == AsyncNameResolver::STATUS_SUCCESS ||
  418. _asyncNameResolver->getStatus() == AsyncNameResolver::STATUS_ERROR;
  419. }
  420. #endif // ENABLE_ASYNC_DNS
  421. void AbstractCommand::prepareForNextAction(Command* nextCommand)
  422. {
  423. CheckIntegrityEntryHandle entry(new StreamCheckIntegrityEntry(req, _requestGroup, nextCommand));
  424. std::deque<Command*> commands;
  425. _requestGroup->processCheckIntegrityEntry(commands, entry, e);
  426. e->addCommand(commands);
  427. e->setNoWait(true);
  428. }
  429. void AbstractCommand::checkIfConnectionEstablished
  430. (const SharedHandle<SocketCore>& socket)
  431. {
  432. if(socket->isReadable(0)) {
  433. std::string error = socket->getSocketError();
  434. if(!error.empty()) {
  435. // Don't set error if proxy server is used and its method is GET.
  436. if(resolveProxyMethod(req->getProtocol()) != V_GET ||
  437. !isProxyRequest(req->getProtocol(), e->option)) {
  438. e->_requestGroupMan->getOrCreateServerStat
  439. (req->getHost(), req->getProtocol())->setError();
  440. }
  441. throw DlRetryEx
  442. (StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()).str());
  443. }
  444. }
  445. }
  446. const std::string& AbstractCommand::resolveProxyMethod
  447. (const std::string& protocol) const
  448. {
  449. if(e->option->get(PREF_PROXY_METHOD) == V_TUNNEL ||
  450. Request::PROTO_HTTPS == protocol) {
  451. return V_TUNNEL;
  452. } else {
  453. return V_GET;
  454. }
  455. }
  456. } // namespace aria2