AbstractCommand.cc 14 KB

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