AbstractCommand.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 "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 "CreateRequestCommand.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. #include "LogFactory.h"
  64. #include "DownloadContext.h"
  65. namespace aria2 {
  66. AbstractCommand::AbstractCommand(int32_t cuid,
  67. const SharedHandle<Request>& req,
  68. const SharedHandle<FileEntry>& fileEntry,
  69. RequestGroup* requestGroup,
  70. DownloadEngine* e,
  71. const SocketHandle& s):
  72. Command(cuid), _requestGroup(requestGroup),
  73. req(req), _fileEntry(fileEntry), e(e), socket(s),
  74. checkSocketIsReadable(false), checkSocketIsWritable(false),
  75. nameResolverCheck(false)
  76. {
  77. if(!socket.isNull() && socket->isOpen()) {
  78. setReadCheckSocket(socket);
  79. }
  80. timeout = _requestGroup->getTimeout();
  81. _requestGroup->increaseStreamConnection();
  82. _requestGroup->increaseNumCommand();
  83. }
  84. AbstractCommand::~AbstractCommand() {
  85. disableReadCheckSocket();
  86. disableWriteCheckSocket();
  87. #ifdef ENABLE_ASYNC_DNS
  88. disableNameResolverCheck(_asyncNameResolver);
  89. #endif // ENABLE_ASYNC_DNS
  90. _requestGroup->decreaseNumCommand();
  91. _requestGroup->decreaseStreamConnection();
  92. }
  93. bool AbstractCommand::execute() {
  94. logger->debug("CUID#%d - socket: read:%d, write:%d, hup:%d, err:%d",
  95. cuid, _readEvent, _writeEvent, _hupEvent, _errorEvent);
  96. try {
  97. if(_requestGroup->downloadFinished() || _requestGroup->isHaltRequested()) {
  98. //logger->debug("CUID#%d - finished.", cuid);
  99. return true;
  100. }
  101. // TODO1.5 it is not needed to check other PeerStats every time.
  102. // Find faster Request when this is the only active Request
  103. if(!req.isNull() && _requestGroup->getNumStreamConnection() == 1 &&
  104. _fileEntry->countPooledRequest() > 0) {
  105. SharedHandle<Request> fasterRequest = _fileEntry->findFasterRequest(req);
  106. if(!fasterRequest.isNull()) {
  107. logger->info("CUID#%d - Use faster Request hostname=%s, port=%u",
  108. cuid,
  109. fasterRequest->getHost().c_str(),
  110. fasterRequest->getPort());
  111. // Cancel current Request object and use faster one.
  112. _fileEntry->removeRequest(req);
  113. Command* command =
  114. InitiateConnectionCommandFactory::createInitiateConnectionCommand
  115. (cuid, fasterRequest, _fileEntry, _requestGroup, e);
  116. e->setNoWait(true);
  117. e->commands.push_back(command);
  118. return true;
  119. }
  120. }
  121. if((checkSocketIsReadable && _readEvent) ||
  122. (checkSocketIsWritable && _writeEvent) ||
  123. _hupEvent ||
  124. #ifdef ENABLE_ASYNC_DNS
  125. (nameResolverCheck && nameResolveFinished()) ||
  126. #endif // ENABLE_ASYNC_DNS
  127. (!checkSocketIsReadable && !checkSocketIsWritable && !nameResolverCheck)) {
  128. checkPoint.reset();
  129. if(!_requestGroup->getPieceStorage().isNull()) {
  130. _segments.clear();
  131. _requestGroup->getSegmentMan()->getInFlightSegment(_segments, cuid);
  132. if(req.isNull() || req->getMaxPipelinedRequest() == 1 ||
  133. _requestGroup->getDownloadContext()->getFileEntries().size() == 1) {
  134. if(_segments.empty()) {
  135. SharedHandle<Segment> segment =
  136. _requestGroup->getSegmentMan()->getSegment(cuid);
  137. if(!segment.isNull()) {
  138. _segments.push_back(segment);
  139. }
  140. }
  141. if(_segments.empty()) {
  142. // TODO socket could be pooled here if pipelining is enabled...
  143. logger->info(MSG_NO_SEGMENT_AVAILABLE, cuid);
  144. return prepareForRetry(1);
  145. }
  146. } else {
  147. size_t maxSegments = req->getMaxPipelinedRequest();
  148. if(_segments.size() < maxSegments) {
  149. _requestGroup->getSegmentMan()->getSegment
  150. (_segments, cuid, _fileEntry, maxSegments);
  151. }
  152. if(_segments.empty()) {
  153. return prepareForRetry(0);
  154. }
  155. }
  156. }
  157. return executeInternal();
  158. } else if(_errorEvent) {
  159. throw DL_RETRY_EX
  160. (StringFormat(MSG_NETWORK_PROBLEM,
  161. socket->getSocketError().c_str()).str());
  162. } else {
  163. if(checkPoint.elapsed(timeout)) {
  164. // timeout triggers ServerStat error state.
  165. SharedHandle<ServerStat> ss =
  166. e->_requestGroupMan->getOrCreateServerStat(req->getHost(),
  167. req->getProtocol());
  168. ss->setError();
  169. throw DL_RETRY_EX2(EX_TIME_OUT, downloadresultcode::TIME_OUT);
  170. }
  171. e->commands.push_back(this);
  172. return false;
  173. }
  174. } catch(DlAbortEx& err) {
  175. if(req.isNull()) {
  176. logger->debug(EX_EXCEPTION_CAUGHT, err);
  177. } else {
  178. logger->error(MSG_DOWNLOAD_ABORTED,
  179. DL_ABORT_EX2(StringFormat
  180. ("URI=%s", req->getCurrentUrl().c_str()).str(),err),
  181. cuid, req->getUrl().c_str());
  182. _fileEntry->addURIResult(req->getUrl(), err.getCode());
  183. _requestGroup->setLastUriResult(req->getUrl(), err.getCode());
  184. }
  185. onAbort();
  186. tryReserved();
  187. return true;
  188. } catch(DlRetryEx& err) {
  189. // TODO1.5 Consider the case when req is null
  190. logger->info(MSG_RESTARTING_DOWNLOAD,
  191. DL_RETRY_EX2(StringFormat
  192. ("URI=%s", req->getCurrentUrl().c_str()).str(),err),
  193. cuid, req->getUrl().c_str());
  194. req->addTryCount();
  195. req->resetRedirectCount();
  196. const unsigned int maxTries = getOption()->getAsInt(PREF_MAX_TRIES);
  197. bool isAbort = maxTries != 0 && req->getTryCount() >= maxTries;
  198. if(isAbort) {
  199. onAbort();
  200. logger->info(MSG_MAX_TRY, cuid, req->getTryCount());
  201. logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str());
  202. _fileEntry->addURIResult(req->getUrl(), err.getCode());
  203. _requestGroup->setLastUriResult(req->getUrl(), err.getCode());
  204. tryReserved();
  205. return true;
  206. } else {
  207. return prepareForRetry(getOption()->getAsInt(PREF_RETRY_WAIT));
  208. }
  209. } catch(DownloadFailureException& err) {
  210. // TODO1.5 Consider the case when req is null
  211. logger->error(EX_EXCEPTION_CAUGHT, err);
  212. _fileEntry->addURIResult(req->getUrl(), err.getCode());
  213. _requestGroup->setLastUriResult(req->getUrl(), err.getCode());
  214. _requestGroup->setHaltRequested(true);
  215. return true;
  216. }
  217. }
  218. void AbstractCommand::tryReserved() {
  219. if(_requestGroup->getDownloadContext()->getFileEntries().size() == 1) {
  220. const SharedHandle<FileEntry>& entry =
  221. _requestGroup->getDownloadContext()->getFirstFileEntry();
  222. // Don't create new command if currently file length is unknown
  223. // and there are no URI left. Because file length is unknown, we
  224. // can assume that there are no in-flight request object.
  225. if(entry->getLength() == 0 && entry->getRemainingUris().size() == 0) {
  226. return;
  227. }
  228. }
  229. Commands commands;
  230. _requestGroup->createNextCommand(commands, e, 1);
  231. e->setNoWait(true);
  232. e->addCommand(commands);
  233. }
  234. bool AbstractCommand::prepareForRetry(time_t wait) {
  235. if(!_requestGroup->getPieceStorage().isNull()) {
  236. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  237. }
  238. if(!req.isNull()) {
  239. _fileEntry->poolRequest(req);
  240. logger->debug("CUID#%d - Pooling request URI=%s",
  241. cuid, req->getUrl().c_str());
  242. if(!_requestGroup->getSegmentMan().isNull()) {
  243. _requestGroup->getSegmentMan()->recognizeSegmentFor(_fileEntry);
  244. }
  245. }
  246. Command* command = new CreateRequestCommand(cuid, _requestGroup, e);
  247. if(wait == 0) {
  248. e->setNoWait(true);
  249. e->commands.push_back(command);
  250. } else {
  251. SleepCommand* scom = new SleepCommand(cuid, e, _requestGroup,
  252. command, wait);
  253. e->commands.push_back(scom);
  254. }
  255. return true;
  256. }
  257. void AbstractCommand::onAbort() {
  258. if(!req.isNull()) {
  259. logger->debug(req->getCurrentUrl().c_str());
  260. // TODO This might be a problem if the failure is caused by proxy.
  261. e->_requestGroupMan->getOrCreateServerStat(req->getHost(),
  262. req->getProtocol())->setError();
  263. _fileEntry->removeIdenticalURI(req->getUrl());
  264. _fileEntry->removeRequest(req);
  265. }
  266. logger->debug(MSG_UNREGISTER_CUID, cuid);
  267. //_segmentMan->unregisterId(cuid);
  268. if(!_requestGroup->getPieceStorage().isNull()) {
  269. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  270. }
  271. }
  272. void AbstractCommand::disableReadCheckSocket() {
  273. if(checkSocketIsReadable) {
  274. e->deleteSocketForReadCheck(readCheckTarget, this);
  275. checkSocketIsReadable = false;
  276. readCheckTarget = SocketHandle();
  277. }
  278. }
  279. void AbstractCommand::setReadCheckSocket(const SocketHandle& socket) {
  280. if(!socket->isOpen()) {
  281. disableReadCheckSocket();
  282. } else {
  283. if(checkSocketIsReadable) {
  284. if(readCheckTarget != socket) {
  285. e->deleteSocketForReadCheck(readCheckTarget, this);
  286. e->addSocketForReadCheck(socket, this);
  287. readCheckTarget = socket;
  288. }
  289. } else {
  290. e->addSocketForReadCheck(socket, this);
  291. checkSocketIsReadable = true;
  292. readCheckTarget = socket;
  293. }
  294. }
  295. }
  296. void AbstractCommand::setReadCheckSocketIf
  297. (const SharedHandle<SocketCore>& socket, bool pred)
  298. {
  299. if(pred) {
  300. setReadCheckSocket(socket);
  301. } else {
  302. disableReadCheckSocket();
  303. }
  304. }
  305. void AbstractCommand::disableWriteCheckSocket() {
  306. if(checkSocketIsWritable) {
  307. e->deleteSocketForWriteCheck(writeCheckTarget, this);
  308. checkSocketIsWritable = false;
  309. writeCheckTarget = SocketHandle();
  310. }
  311. }
  312. void AbstractCommand::setWriteCheckSocket(const SocketHandle& socket) {
  313. if(!socket->isOpen()) {
  314. disableWriteCheckSocket();
  315. } else {
  316. if(checkSocketIsWritable) {
  317. if(writeCheckTarget != socket) {
  318. e->deleteSocketForWriteCheck(writeCheckTarget, this);
  319. e->addSocketForWriteCheck(socket, this);
  320. writeCheckTarget = socket;
  321. }
  322. } else {
  323. e->addSocketForWriteCheck(socket, this);
  324. checkSocketIsWritable = true;
  325. writeCheckTarget = socket;
  326. }
  327. }
  328. }
  329. void AbstractCommand::setWriteCheckSocketIf
  330. (const SharedHandle<SocketCore>& socket, bool pred)
  331. {
  332. if(pred) {
  333. setWriteCheckSocket(socket);
  334. } else {
  335. disableWriteCheckSocket();
  336. }
  337. }
  338. static const std::string& getProxyStringFor(const std::string& proxyPref,
  339. const SharedHandle<Option>& option)
  340. {
  341. if(option->defined(proxyPref)) {
  342. return option->get(proxyPref);
  343. } else {
  344. return option->get(PREF_ALL_PROXY);
  345. }
  346. }
  347. static bool isProxyUsed(const std::string& proxyPref,
  348. const SharedHandle<Option>& option)
  349. {
  350. std::string proxy = getProxyStringFor(proxyPref, option);
  351. if(proxy.empty()) {
  352. return false;
  353. } else {
  354. return Request().setUrl(proxy);
  355. }
  356. }
  357. static bool isProxyRequest(const std::string& protocol,
  358. const SharedHandle<Option>& option)
  359. {
  360. return
  361. (protocol == Request::PROTO_HTTP && isProxyUsed(PREF_HTTP_PROXY, option)) ||
  362. (protocol == Request::PROTO_HTTPS && isProxyUsed(PREF_HTTPS_PROXY,option))||
  363. (protocol == Request::PROTO_FTP && isProxyUsed(PREF_FTP_PROXY, option));
  364. }
  365. class DomainMatch {
  366. private:
  367. std::string _hostname;
  368. public:
  369. DomainMatch(const std::string& hostname):_hostname(hostname) {}
  370. bool operator()(const std::string& domain) const
  371. {
  372. if(Util::startsWith(domain, ".")) {
  373. return Util::endsWith(_hostname, domain);
  374. } else {
  375. return Util::endsWith(_hostname, "."+domain);
  376. }
  377. }
  378. };
  379. static bool inNoProxy(const SharedHandle<Request>& req,
  380. const std::string& noProxy)
  381. {
  382. std::deque<std::string> entries;
  383. Util::slice(entries, noProxy, ',', true);
  384. if(entries.empty()) {
  385. return false;
  386. }
  387. return
  388. std::find_if(entries.begin(), entries.end(),
  389. DomainMatch("."+req->getHost())) != entries.end();
  390. }
  391. bool AbstractCommand::isProxyDefined() const
  392. {
  393. return isProxyRequest(req->getProtocol(), getOption()) &&
  394. !inNoProxy(req, getOption()->get(PREF_NO_PROXY));
  395. }
  396. static const std::string& getProxyString(const SharedHandle<Request>& req,
  397. const SharedHandle<Option>& option)
  398. {
  399. if(req->getProtocol() == Request::PROTO_HTTP) {
  400. return getProxyStringFor(PREF_HTTP_PROXY, option);
  401. } else if(req->getProtocol() == Request::PROTO_HTTPS) {
  402. return getProxyStringFor(PREF_HTTPS_PROXY, option);
  403. } else if(req->getProtocol() == Request::PROTO_FTP) {
  404. return getProxyStringFor(PREF_FTP_PROXY, option);
  405. } else {
  406. return A2STR::NIL;
  407. }
  408. }
  409. SharedHandle<Request> AbstractCommand::createProxyRequest() const
  410. {
  411. SharedHandle<Request> proxyRequest;
  412. if(inNoProxy(req, getOption()->get(PREF_NO_PROXY))) {
  413. return proxyRequest;
  414. }
  415. std::string proxy = getProxyString(req, getOption());
  416. if(!proxy.empty()) {
  417. proxyRequest.reset(new Request());
  418. if(proxyRequest->setUrl(proxy)) {
  419. logger->debug("CUID#%d - Using proxy", cuid);
  420. } else {
  421. logger->debug("CUID#%d - Failed to parse proxy string", cuid);
  422. proxyRequest.reset();
  423. }
  424. }
  425. return proxyRequest;
  426. }
  427. #ifdef ENABLE_ASYNC_DNS
  428. bool AbstractCommand::isAsyncNameResolverInitialized() const
  429. {
  430. return !_asyncNameResolver.isNull();
  431. }
  432. void AbstractCommand::initAsyncNameResolver(const std::string& hostname)
  433. {
  434. _asyncNameResolver.reset(new AsyncNameResolver());
  435. logger->info(MSG_RESOLVING_HOSTNAME, cuid, hostname.c_str());
  436. _asyncNameResolver->resolve(hostname);
  437. setNameResolverCheck(_asyncNameResolver);
  438. }
  439. bool AbstractCommand::asyncResolveHostname()
  440. {
  441. switch(_asyncNameResolver->getStatus()) {
  442. case AsyncNameResolver::STATUS_SUCCESS:
  443. return true;
  444. case AsyncNameResolver::STATUS_ERROR:
  445. if(!isProxyRequest(req->getProtocol(), getOption())) {
  446. e->_requestGroupMan->getOrCreateServerStat
  447. (req->getHost(), req->getProtocol())->setError();
  448. }
  449. throw DL_ABORT_EX(StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid,
  450. _asyncNameResolver->getHostname().c_str(),
  451. _asyncNameResolver->getError().c_str()).str());
  452. default:
  453. return false;
  454. }
  455. }
  456. const std::deque<std::string>& AbstractCommand::getResolvedAddresses()
  457. {
  458. return _asyncNameResolver->getResolvedAddresses();
  459. }
  460. void AbstractCommand::setNameResolverCheck
  461. (const SharedHandle<AsyncNameResolver>& resolver) {
  462. if(!resolver.isNull()) {
  463. nameResolverCheck = true;
  464. e->addNameResolverCheck(resolver, this);
  465. }
  466. }
  467. void AbstractCommand::disableNameResolverCheck
  468. (const SharedHandle<AsyncNameResolver>& resolver) {
  469. if(!resolver.isNull()) {
  470. nameResolverCheck = false;
  471. e->deleteNameResolverCheck(resolver, this);
  472. }
  473. }
  474. bool AbstractCommand::nameResolveFinished() const {
  475. return
  476. _asyncNameResolver->getStatus() == AsyncNameResolver::STATUS_SUCCESS ||
  477. _asyncNameResolver->getStatus() == AsyncNameResolver::STATUS_ERROR;
  478. }
  479. #endif // ENABLE_ASYNC_DNS
  480. void AbstractCommand::prepareForNextAction(Command* nextCommand)
  481. {
  482. CheckIntegrityEntryHandle entry
  483. (new StreamCheckIntegrityEntry(_requestGroup, nextCommand));
  484. std::deque<Command*> commands;
  485. _requestGroup->processCheckIntegrityEntry(commands, entry, e);
  486. e->addCommand(commands);
  487. e->setNoWait(true);
  488. }
  489. bool AbstractCommand::checkIfConnectionEstablished
  490. (const SharedHandle<SocketCore>& socket,
  491. const std::string& connectedHostname,
  492. const std::string& connectedAddr,
  493. uint16_t connectedPort)
  494. {
  495. if(socket->isReadable(0)) {
  496. std::string error = socket->getSocketError();
  497. if(!error.empty()) {
  498. e->markBadIPAddress(connectedHostname, connectedAddr, connectedPort);
  499. if(!e->findCachedIPAddress(connectedHostname, connectedPort).empty()) {
  500. logger->info("CUID#%d - Could not to connect to %s:%u."
  501. " Trying another address",
  502. cuid, connectedAddr.c_str(), connectedPort);
  503. Command* command =
  504. InitiateConnectionCommandFactory::createInitiateConnectionCommand
  505. (cuid, req, _fileEntry, _requestGroup, e);
  506. e->setNoWait(true);
  507. e->commands.push_back(command);
  508. return false;
  509. }
  510. e->removeCachedIPAddress(connectedHostname, connectedPort);
  511. // Don't set error if proxy server is used and its method is GET.
  512. if(resolveProxyMethod(req->getProtocol()) != V_GET ||
  513. !isProxyRequest(req->getProtocol(), getOption())) {
  514. e->_requestGroupMan->getOrCreateServerStat
  515. (req->getHost(), req->getProtocol())->setError();
  516. }
  517. throw DL_RETRY_EX
  518. (StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()).str());
  519. }
  520. }
  521. return true;
  522. }
  523. const std::string& AbstractCommand::resolveProxyMethod
  524. (const std::string& protocol) const
  525. {
  526. if(getOption()->get(PREF_PROXY_METHOD) == V_TUNNEL ||
  527. Request::PROTO_HTTPS == protocol) {
  528. return V_TUNNEL;
  529. } else {
  530. return V_GET;
  531. }
  532. }
  533. const SharedHandle<Option>& AbstractCommand::getOption() const
  534. {
  535. return _requestGroup->getOption();
  536. }
  537. } // namespace aria2