AbstractCommand.cc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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. #include "wallclock.h"
  66. #include "NameResolver.h"
  67. #include "ServerStatMan.h"
  68. #include "FileAllocationEntry.h"
  69. #ifdef ENABLE_MESSAGE_DIGEST
  70. # include "ChecksumCheckIntegrityEntry.h"
  71. #endif // ENABLE_MESSAGE_DIGEST
  72. namespace aria2 {
  73. AbstractCommand::AbstractCommand(cuid_t cuid,
  74. const SharedHandle<Request>& req,
  75. const SharedHandle<FileEntry>& fileEntry,
  76. RequestGroup* requestGroup,
  77. DownloadEngine* e,
  78. const SocketHandle& s,
  79. bool incNumConnection):
  80. Command(cuid), checkPoint_(global::wallclock),
  81. timeout_(requestGroup->getTimeout()),
  82. requestGroup_(requestGroup),
  83. req_(req), fileEntry_(fileEntry), e_(e), socket_(s),
  84. checkSocketIsReadable_(false), checkSocketIsWritable_(false),
  85. nameResolverCheck_(false),
  86. incNumConnection_(incNumConnection)
  87. {
  88. if(!socket_.isNull() && socket_->isOpen()) {
  89. setReadCheckSocket(socket_);
  90. }
  91. if(incNumConnection_) {
  92. requestGroup->increaseStreamConnection();
  93. }
  94. requestGroup_->increaseStreamCommand();
  95. requestGroup_->increaseNumCommand();
  96. }
  97. AbstractCommand::~AbstractCommand() {
  98. disableReadCheckSocket();
  99. disableWriteCheckSocket();
  100. #ifdef ENABLE_ASYNC_DNS
  101. disableNameResolverCheck(asyncNameResolver_);
  102. #endif // ENABLE_ASYNC_DNS
  103. requestGroup_->decreaseNumCommand();
  104. requestGroup_->decreaseStreamCommand();
  105. if(incNumConnection_) {
  106. requestGroup_->decreaseStreamConnection();
  107. }
  108. }
  109. bool AbstractCommand::execute() {
  110. if(getLogger()->debug()) {
  111. getLogger()->debug("CUID#%s - socket: read:%d, write:%d, hup:%d, err:%d",
  112. util::itos(getCuid()).c_str(),
  113. readEventEnabled(),
  114. writeEventEnabled(),
  115. hupEventEnabled(),
  116. errorEventEnabled());
  117. }
  118. try {
  119. if(requestGroup_->downloadFinished() || requestGroup_->isHaltRequested()) {
  120. return true;
  121. }
  122. if(!req_.isNull() && req_->removalRequested()) {
  123. if(getLogger()->debug()) {
  124. getLogger()->debug
  125. ("CUID#%s - Discard original URI=%s because it is requested.",
  126. util::itos(getCuid()).c_str(), req_->getUri().c_str());
  127. }
  128. return prepareForRetry(0);
  129. }
  130. if(!getPieceStorage().isNull()) {
  131. segments_.clear();
  132. getSegmentMan()->getInFlightSegment(segments_, getCuid());
  133. if(!req_.isNull() && segments_.empty()) {
  134. // This command previously has assigned segments, but it is
  135. // canceled. So discard current request chain. Plus, if no
  136. // segment is available when http pipelining is used.
  137. if(getLogger()->debug()) {
  138. getLogger()->debug("CUID#%s - It seems previously assigned segments"
  139. " are canceled. Restart.",
  140. util::itos(getCuid()).c_str());
  141. }
  142. // Request::isPipeliningEnabled() == true means aria2
  143. // accessed the remote server and discovered that the server
  144. // supports pipelining.
  145. if(!req_.isNull() && req_->isPipeliningEnabled()) {
  146. e_->poolSocket(req_, createProxyRequest(), socket_);
  147. }
  148. return prepareForRetry(0);
  149. }
  150. // TODO it is not needed to check other PeerStats every time.
  151. // Find faster Request when no segment is available.
  152. if(!req_.isNull() && fileEntry_->countPooledRequest() > 0 &&
  153. !getPieceStorage()->hasMissingUnusedPiece()) {
  154. SharedHandle<Request> fasterRequest = fileEntry_->findFasterRequest(req_);
  155. if(!fasterRequest.isNull()) {
  156. if(getLogger()->info()) {
  157. getLogger()->info("CUID#%s - Use faster Request hostname=%s, port=%u",
  158. util::itos(getCuid()).c_str(),
  159. fasterRequest->getHost().c_str(),
  160. fasterRequest->getPort());
  161. }
  162. // Cancel current Request object and use faster one.
  163. fileEntry_->removeRequest(req_);
  164. Command* command =
  165. InitiateConnectionCommandFactory::createInitiateConnectionCommand
  166. (getCuid(), fasterRequest, fileEntry_, requestGroup_, e_);
  167. e_->setNoWait(true);
  168. e_->addCommand(command);
  169. return true;
  170. }
  171. }
  172. }
  173. if((checkSocketIsReadable_ && readEventEnabled()) ||
  174. (checkSocketIsWritable_ && writeEventEnabled()) ||
  175. hupEventEnabled() ||
  176. #ifdef ENABLE_ASYNC_DNS
  177. (nameResolverCheck_ && nameResolveFinished()) ||
  178. #endif // ENABLE_ASYNC_DNS
  179. (!checkSocketIsReadable_ && !checkSocketIsWritable_ &&
  180. !nameResolverCheck_)) {
  181. checkPoint_ = global::wallclock;
  182. if(!getPieceStorage().isNull()) {
  183. if(req_.isNull() || req_->getMaxPipelinedRequest() == 1 ||
  184. // Why the following condition is necessary? That's because
  185. // For single file download, SegmentMan::getSegment(cuid)
  186. // is more efficient.
  187. getDownloadContext()->getFileEntries().size() == 1) {
  188. size_t maxSegments = req_.isNull()?1:req_->getMaxPipelinedRequest();
  189. size_t minSplitSize = calculateMinSplitSize();
  190. while(segments_.size() < maxSegments) {
  191. SharedHandle<Segment> segment =
  192. getSegmentMan()->getSegment(getCuid(), minSplitSize);
  193. if(segment.isNull()) {
  194. break;
  195. } else {
  196. segments_.push_back(segment);
  197. }
  198. }
  199. if(segments_.empty()) {
  200. // TODO socket could be pooled here if pipelining is
  201. // enabled... Hmm, I don't think if pipelining is enabled
  202. // it does not go here.
  203. if(getLogger()->info()) {
  204. getLogger()->info(MSG_NO_SEGMENT_AVAILABLE,
  205. util::itos(getCuid()).c_str());
  206. }
  207. // When all segments are ignored in SegmentMan, there are
  208. // no URIs available, so don't retry.
  209. if(getSegmentMan()->allSegmentsIgnored()) {
  210. if(getLogger()->debug()) {
  211. getLogger()->debug("All segments are ignored.");
  212. }
  213. return true;
  214. } else {
  215. return prepareForRetry(1);
  216. }
  217. }
  218. } else {
  219. // For multi-file downloads
  220. size_t minSplitSize = calculateMinSplitSize();
  221. size_t maxSegments = req_->getMaxPipelinedRequest();
  222. if(segments_.size() < maxSegments) {
  223. getSegmentMan()->getSegment
  224. (segments_, getCuid(), minSplitSize, fileEntry_, maxSegments);
  225. }
  226. if(segments_.empty()) {
  227. return prepareForRetry(0);
  228. }
  229. }
  230. }
  231. return executeInternal();
  232. } else if(errorEventEnabled()) {
  233. throw DL_RETRY_EX
  234. (StringFormat(MSG_NETWORK_PROBLEM,
  235. socket_->getSocketError().c_str()).str());
  236. } else {
  237. if(checkPoint_.difference(global::wallclock) >= timeout_) {
  238. // timeout triggers ServerStat error state.
  239. SharedHandle<ServerStat> ss =
  240. e_->getRequestGroupMan()->getOrCreateServerStat(req_->getHost(),
  241. req_->getProtocol());
  242. ss->setError();
  243. // Purging IP address cache to renew IP address.
  244. if(getLogger()->debug()) {
  245. getLogger()->debug("CUID#%s - Marking IP address %s as bad",
  246. util::itos(getCuid()).c_str(),
  247. req_->getConnectedAddr().c_str());
  248. }
  249. e_->markBadIPAddress(req_->getConnectedHostname(),
  250. req_->getConnectedAddr(),
  251. req_->getConnectedPort());
  252. if(e_->findCachedIPAddress
  253. (req_->getConnectedHostname(), req_->getConnectedPort()).empty()) {
  254. if(getLogger()->debug()) {
  255. getLogger()->debug("CUID#%s - All IP addresses were marked bad."
  256. " Removing Entry.",
  257. util::itos(getCuid()).c_str());
  258. }
  259. e_->removeCachedIPAddress
  260. (req_->getConnectedHostname(), req_->getConnectedPort());
  261. }
  262. throw DL_RETRY_EX2(EX_TIME_OUT, downloadresultcode::TIME_OUT);
  263. }
  264. e_->addCommand(this);
  265. return false;
  266. }
  267. } catch(DlAbortEx& err) {
  268. if(req_.isNull()) {
  269. if(getLogger()->debug()) {
  270. getLogger()->debug(EX_EXCEPTION_CAUGHT, err);
  271. }
  272. } else {
  273. getLogger()->error
  274. (MSG_DOWNLOAD_ABORTED,
  275. DL_ABORT_EX2(StringFormat
  276. ("URI=%s", req_->getCurrentUri().c_str()).str(),err),
  277. util::itos(getCuid()).c_str(), req_->getUri().c_str());
  278. fileEntry_->addURIResult(req_->getUri(), err.getCode());
  279. requestGroup_->setLastUriResult(req_->getUri(), err.getCode());
  280. if(err.getCode() == downloadresultcode::CANNOT_RESUME) {
  281. requestGroup_->increaseResumeFailureCount();
  282. }
  283. }
  284. onAbort();
  285. tryReserved();
  286. return true;
  287. } catch(DlRetryEx& err) {
  288. assert(!req_.isNull());
  289. if(getLogger()->info()) {
  290. getLogger()->info
  291. (MSG_RESTARTING_DOWNLOAD,
  292. DL_RETRY_EX2(StringFormat
  293. ("URI=%s", req_->getCurrentUri().c_str()).str(),
  294. err),
  295. util::itos(getCuid()).c_str(), req_->getUri().c_str());
  296. }
  297. req_->addTryCount();
  298. req_->resetRedirectCount();
  299. req_->resetUri();
  300. const unsigned int maxTries = getOption()->getAsInt(PREF_MAX_TRIES);
  301. bool isAbort = maxTries != 0 && req_->getTryCount() >= maxTries;
  302. if(isAbort) {
  303. if(getLogger()->info()) {
  304. getLogger()->info(MSG_MAX_TRY,
  305. util::itos(getCuid()).c_str(), req_->getTryCount());
  306. }
  307. getLogger()->error(MSG_DOWNLOAD_ABORTED, err,
  308. util::itos(getCuid()).c_str(),
  309. req_->getUri().c_str());
  310. fileEntry_->addURIResult(req_->getUri(), err.getCode());
  311. requestGroup_->setLastUriResult(req_->getUri(), err.getCode());
  312. if(err.getCode() == downloadresultcode::CANNOT_RESUME) {
  313. requestGroup_->increaseResumeFailureCount();
  314. }
  315. onAbort();
  316. tryReserved();
  317. return true;
  318. } else {
  319. return prepareForRetry(0);
  320. }
  321. } catch(DownloadFailureException& err) {
  322. getLogger()->error(EX_EXCEPTION_CAUGHT, err);
  323. if(!req_.isNull()) {
  324. fileEntry_->addURIResult(req_->getUri(), err.getCode());
  325. requestGroup_->setLastUriResult(req_->getUri(), err.getCode());
  326. }
  327. requestGroup_->setHaltRequested(true);
  328. return true;
  329. }
  330. }
  331. void AbstractCommand::tryReserved() {
  332. if(getDownloadContext()->getFileEntries().size() == 1) {
  333. const SharedHandle<FileEntry>& entry =
  334. getDownloadContext()->getFirstFileEntry();
  335. // Don't create new command if currently file length is unknown
  336. // and there are no URI left. Because file length is unknown, we
  337. // can assume that there are no in-flight request object.
  338. if(entry->getLength() == 0 && entry->getRemainingUris().empty()) {
  339. if(getLogger()->debug()) {
  340. getLogger()->debug("CUID#%s - Not trying next request."
  341. " No reserved/pooled request is remaining and"
  342. " total length is still unknown.",
  343. util::itos(getCuid()).c_str());
  344. }
  345. return;
  346. }
  347. }
  348. if(getLogger()->debug()) {
  349. getLogger()->debug("CUID#%s - Trying reserved/pooled request.",
  350. util::itos(getCuid()).c_str());
  351. }
  352. std::vector<Command*> commands;
  353. requestGroup_->createNextCommand(commands, e_, 1);
  354. e_->setNoWait(true);
  355. e_->addCommand(commands);
  356. }
  357. bool AbstractCommand::prepareForRetry(time_t wait) {
  358. if(!getPieceStorage().isNull()) {
  359. getSegmentMan()->cancelSegment(getCuid());
  360. }
  361. if(!req_.isNull()) {
  362. fileEntry_->poolRequest(req_);
  363. if(getLogger()->debug()) {
  364. getLogger()->debug("CUID#%s - Pooling request URI=%s",
  365. util::itos(getCuid()).c_str(), req_->getUri().c_str());
  366. }
  367. if(!getSegmentMan().isNull()) {
  368. getSegmentMan()->recognizeSegmentFor(fileEntry_);
  369. }
  370. }
  371. Command* command = new CreateRequestCommand(getCuid(), requestGroup_, e_);
  372. if(wait == 0) {
  373. e_->setNoWait(true);
  374. e_->addCommand(command);
  375. } else {
  376. SleepCommand* scom = new SleepCommand(getCuid(), e_, requestGroup_,
  377. command, wait);
  378. e_->addCommand(scom);
  379. }
  380. return true;
  381. }
  382. void AbstractCommand::onAbort() {
  383. if(!req_.isNull()) {
  384. // TODO This might be a problem if the failure is caused by proxy.
  385. e_->getRequestGroupMan()->getOrCreateServerStat
  386. (req_->getHost(), req_->getProtocol())->setError();
  387. fileEntry_->removeIdenticalURI(req_->getUri());
  388. fileEntry_->removeRequest(req_);
  389. }
  390. if(getLogger()->debug()) {
  391. getLogger()->debug("CUID#%s - Aborting download",
  392. util::itos(getCuid()).c_str());
  393. }
  394. if(!getPieceStorage().isNull()) {
  395. getSegmentMan()->cancelSegment(getCuid());
  396. // Don't do following process if BitTorrent is involved or files
  397. // in DownloadContext is more than 1. The latter condition is
  398. // limitation of current implementation.
  399. if(!getOption()->getAsBool(PREF_ALWAYS_RESUME) &&
  400. !fileEntry_.isNull() &&
  401. getSegmentMan()->calculateSessionDownloadLength() == 0 &&
  402. !requestGroup_->p2pInvolved() &&
  403. getDownloadContext()->getFileEntries().size() == 1) {
  404. const int maxTries = getOption()->getAsInt(PREF_MAX_RESUME_FAILURE_TRIES);
  405. if((maxTries > 0 && requestGroup_->getResumeFailureCount() >= maxTries)||
  406. fileEntry_->emptyRequestUri()) {
  407. // Local file exists, but given servers(or at least contacted
  408. // ones) doesn't support resume. Let's restart download from
  409. // scratch.
  410. getLogger()->notice("CUID#%s - Failed to resume download."
  411. " Download from scratch.",
  412. util::itos(getCuid()).c_str());
  413. if(getLogger()->debug()) {
  414. getLogger()->debug
  415. ("CUID#%s - Gathering URIs that has CANNOT_RESUME error",
  416. util::itos(getCuid()).c_str());
  417. }
  418. // Set PREF_ALWAYS_RESUME to V_TRUE to avoid repeating this
  419. // process.
  420. getOption()->put(PREF_ALWAYS_RESUME, V_TRUE);
  421. std::deque<URIResult> res;
  422. fileEntry_->extractURIResult(res, downloadresultcode::CANNOT_RESUME);
  423. if(!res.empty()) {
  424. getSegmentMan()->cancelAllSegments();
  425. getSegmentMan()->eraseSegmentWrittenLengthMemo();
  426. getPieceStorage()->markPiecesDone(0);
  427. std::vector<std::string> uris;
  428. uris.reserve(res.size());
  429. std::transform(res.begin(), res.end(), std::back_inserter(uris),
  430. std::mem_fun_ref(&URIResult::getURI));
  431. if(getLogger()->debug()) {
  432. getLogger()->debug("CUID#%s - %lu URIs found.",
  433. util::itos(getCuid()).c_str(),
  434. static_cast<unsigned long int>(uris.size()));
  435. }
  436. fileEntry_->addUris(uris.begin(), uris.end());
  437. getSegmentMan()->recognizeSegmentFor(fileEntry_);
  438. }
  439. }
  440. }
  441. }
  442. }
  443. void AbstractCommand::disableReadCheckSocket() {
  444. if(checkSocketIsReadable_) {
  445. e_->deleteSocketForReadCheck(readCheckTarget_, this);
  446. checkSocketIsReadable_ = false;
  447. readCheckTarget_.reset();
  448. }
  449. }
  450. void AbstractCommand::setReadCheckSocket(const SocketHandle& socket) {
  451. if(!socket->isOpen()) {
  452. disableReadCheckSocket();
  453. } else {
  454. if(checkSocketIsReadable_) {
  455. if(readCheckTarget_ != socket) {
  456. e_->deleteSocketForReadCheck(readCheckTarget_, this);
  457. e_->addSocketForReadCheck(socket, this);
  458. readCheckTarget_ = socket;
  459. }
  460. } else {
  461. e_->addSocketForReadCheck(socket, this);
  462. checkSocketIsReadable_ = true;
  463. readCheckTarget_ = socket;
  464. }
  465. }
  466. }
  467. void AbstractCommand::setReadCheckSocketIf
  468. (const SharedHandle<SocketCore>& socket, bool pred)
  469. {
  470. if(pred) {
  471. setReadCheckSocket(socket);
  472. } else {
  473. disableReadCheckSocket();
  474. }
  475. }
  476. void AbstractCommand::disableWriteCheckSocket() {
  477. if(checkSocketIsWritable_) {
  478. e_->deleteSocketForWriteCheck(writeCheckTarget_, this);
  479. checkSocketIsWritable_ = false;
  480. writeCheckTarget_.reset();
  481. }
  482. }
  483. void AbstractCommand::setWriteCheckSocket(const SocketHandle& socket) {
  484. if(!socket->isOpen()) {
  485. disableWriteCheckSocket();
  486. } else {
  487. if(checkSocketIsWritable_) {
  488. if(writeCheckTarget_ != socket) {
  489. e_->deleteSocketForWriteCheck(writeCheckTarget_, this);
  490. e_->addSocketForWriteCheck(socket, this);
  491. writeCheckTarget_ = socket;
  492. }
  493. } else {
  494. e_->addSocketForWriteCheck(socket, this);
  495. checkSocketIsWritable_ = true;
  496. writeCheckTarget_ = socket;
  497. }
  498. }
  499. }
  500. void AbstractCommand::setWriteCheckSocketIf
  501. (const SharedHandle<SocketCore>& socket, bool pred)
  502. {
  503. if(pred) {
  504. setWriteCheckSocket(socket);
  505. } else {
  506. disableWriteCheckSocket();
  507. }
  508. }
  509. // Returns proxy option value for the given protocol.
  510. static const std::string& getProxyOptionFor
  511. (const std::string& proxyPref, const SharedHandle<Option>& option)
  512. {
  513. if(option->defined(proxyPref)) {
  514. return option->get(proxyPref);
  515. } else {
  516. return option->get(PREF_ALL_PROXY);
  517. }
  518. }
  519. // Returns proxy URI for given protocol. If no proxy URI is defined,
  520. // then returns an empty string.
  521. static const std::string& getProxyUri
  522. (const std::string& protocol, const SharedHandle<Option>& option)
  523. {
  524. if(protocol == Request::PROTO_HTTP) {
  525. return getProxyOptionFor(PREF_HTTP_PROXY, option);
  526. } else if(protocol == Request::PROTO_HTTPS) {
  527. return getProxyOptionFor(PREF_HTTPS_PROXY, option);
  528. } else if(protocol == Request::PROTO_FTP) {
  529. return getProxyOptionFor(PREF_FTP_PROXY, option);
  530. } else {
  531. return A2STR::NIL;
  532. }
  533. }
  534. // Returns true if proxy is defined for the given protocol. Otherwise
  535. // returns false.
  536. static bool isProxyRequest
  537. (const std::string& protocol, const SharedHandle<Option>& option)
  538. {
  539. const std::string& proxyUri = getProxyUri(protocol, option);
  540. return !proxyUri.empty() && Request().setUri(proxyUri);
  541. }
  542. namespace {
  543. class DomainMatch {
  544. private:
  545. std::string hostname_;
  546. public:
  547. DomainMatch(const std::string& hostname):hostname_(hostname) {}
  548. bool operator()(const std::string& domain) const
  549. {
  550. if(util::startsWith(domain, A2STR::DOT_C)) {
  551. return util::endsWith(hostname_, domain);
  552. } else {
  553. return util::endsWith(hostname_, A2STR::DOT_C+domain);
  554. }
  555. }
  556. };
  557. }
  558. static bool inNoProxy(const SharedHandle<Request>& req,
  559. const std::string& noProxy)
  560. {
  561. std::vector<std::string> entries;
  562. util::split(noProxy, std::back_inserter(entries), ",", true);
  563. if(entries.empty()) {
  564. return false;
  565. }
  566. DomainMatch domainMatch(A2STR::DOT_C+req->getHost());
  567. for(std::vector<std::string>::const_iterator i = entries.begin(),
  568. eoi = entries.end(); i != eoi; ++i) {
  569. std::string::size_type slashpos = (*i).find('/');
  570. if(slashpos == std::string::npos) {
  571. if(util::isNumericHost(*i)) {
  572. if(req->getHost() == *i) {
  573. return true;
  574. }
  575. } else if(domainMatch(*i)) {
  576. return true;
  577. }
  578. } else {
  579. if(!util::isNumericHost(req->getHost())) {
  580. // TODO We don't resolve hostname here. More complete
  581. // implementation is that we should first resolve
  582. // hostname(which may result in several IP addresses) and
  583. // evaluates against all of them
  584. continue;
  585. }
  586. std::string ip = (*i).substr(0, slashpos);
  587. uint32_t bits;
  588. if(!util::parseUIntNoThrow(bits, (*i).substr(slashpos+1))) {
  589. continue;
  590. }
  591. if(util::inSameCidrBlock(ip, req->getHost(), bits)) {
  592. return true;
  593. }
  594. }
  595. }
  596. return false;
  597. }
  598. bool AbstractCommand::isProxyDefined() const
  599. {
  600. return isProxyRequest(req_->getProtocol(), getOption()) &&
  601. !inNoProxy(req_, getOption()->get(PREF_NO_PROXY));
  602. }
  603. SharedHandle<Request> AbstractCommand::createProxyRequest() const
  604. {
  605. SharedHandle<Request> proxyRequest;
  606. if(inNoProxy(req_, getOption()->get(PREF_NO_PROXY))) {
  607. return proxyRequest;
  608. }
  609. std::string proxy = getProxyUri(req_->getProtocol(), getOption());
  610. if(!proxy.empty()) {
  611. proxyRequest.reset(new Request());
  612. if(proxyRequest->setUri(proxy)) {
  613. if(getLogger()->debug()) {
  614. getLogger()->debug("CUID#%s - Using proxy",
  615. util::itos(getCuid()).c_str());
  616. }
  617. } else {
  618. if(getLogger()->debug()) {
  619. getLogger()->debug("CUID#%s - Failed to parse proxy string",
  620. util::itos(getCuid()).c_str());
  621. }
  622. proxyRequest.reset();
  623. }
  624. }
  625. return proxyRequest;
  626. }
  627. #ifdef ENABLE_ASYNC_DNS
  628. bool AbstractCommand::isAsyncNameResolverInitialized() const
  629. {
  630. return !asyncNameResolver_.isNull();
  631. }
  632. void AbstractCommand::initAsyncNameResolver(const std::string& hostname)
  633. {
  634. int family;
  635. if(getOption()->getAsBool(PREF_ENABLE_ASYNC_DNS6)) {
  636. family = AF_UNSPEC;
  637. } else {
  638. family = AF_INET;
  639. }
  640. asyncNameResolver_.reset(new AsyncNameResolver(family));
  641. if(getLogger()->info()) {
  642. getLogger()->info(MSG_RESOLVING_HOSTNAME,
  643. util::itos(getCuid()).c_str(), hostname.c_str());
  644. }
  645. asyncNameResolver_->resolve(hostname);
  646. setNameResolverCheck(asyncNameResolver_);
  647. }
  648. bool AbstractCommand::asyncResolveHostname()
  649. {
  650. switch(asyncNameResolver_->getStatus()) {
  651. case AsyncNameResolver::STATUS_SUCCESS:
  652. disableNameResolverCheck(asyncNameResolver_);
  653. return true;
  654. case AsyncNameResolver::STATUS_ERROR:
  655. disableNameResolverCheck(asyncNameResolver_);
  656. if(!isProxyRequest(req_->getProtocol(), getOption())) {
  657. e_->getRequestGroupMan()->getOrCreateServerStat
  658. (req_->getHost(), req_->getProtocol())->setError();
  659. }
  660. throw DL_ABORT_EX
  661. (StringFormat(MSG_NAME_RESOLUTION_FAILED,
  662. util::itos(getCuid()).c_str(),
  663. asyncNameResolver_->getHostname().c_str(),
  664. asyncNameResolver_->getError().c_str()).str());
  665. default:
  666. return false;
  667. }
  668. }
  669. const std::vector<std::string>& AbstractCommand::getResolvedAddresses()
  670. {
  671. return asyncNameResolver_->getResolvedAddresses();
  672. }
  673. void AbstractCommand::setNameResolverCheck
  674. (const SharedHandle<AsyncNameResolver>& resolver) {
  675. if(!resolver.isNull()) {
  676. nameResolverCheck_ = true;
  677. e_->addNameResolverCheck(resolver, this);
  678. }
  679. }
  680. void AbstractCommand::disableNameResolverCheck
  681. (const SharedHandle<AsyncNameResolver>& resolver) {
  682. if(!resolver.isNull()) {
  683. nameResolverCheck_ = false;
  684. e_->deleteNameResolverCheck(resolver, this);
  685. }
  686. }
  687. bool AbstractCommand::nameResolveFinished() const {
  688. return
  689. asyncNameResolver_->getStatus() == AsyncNameResolver::STATUS_SUCCESS ||
  690. asyncNameResolver_->getStatus() == AsyncNameResolver::STATUS_ERROR;
  691. }
  692. #endif // ENABLE_ASYNC_DNS
  693. std::string AbstractCommand::resolveHostname
  694. (std::vector<std::string>& addrs, const std::string& hostname, uint16_t port)
  695. {
  696. if(util::isNumericHost(hostname)) {
  697. addrs.push_back(hostname);
  698. return hostname;
  699. }
  700. e_->findAllCachedIPAddresses(std::back_inserter(addrs), hostname, port);
  701. std::string ipaddr;
  702. if(addrs.empty()) {
  703. #ifdef ENABLE_ASYNC_DNS
  704. if(getOption()->getAsBool(PREF_ASYNC_DNS)) {
  705. if(!isAsyncNameResolverInitialized()) {
  706. initAsyncNameResolver(hostname);
  707. }
  708. if(asyncResolveHostname()) {
  709. addrs = getResolvedAddresses();
  710. } else {
  711. return A2STR::NIL;
  712. }
  713. } else
  714. #endif // ENABLE_ASYNC_DNS
  715. {
  716. NameResolver res;
  717. res.setSocktype(SOCK_STREAM);
  718. if(e_->getOption()->getAsBool(PREF_DISABLE_IPV6)) {
  719. res.setFamily(AF_INET);
  720. }
  721. res.resolve(addrs, hostname);
  722. }
  723. if(getLogger()->info()) {
  724. getLogger()->info(MSG_NAME_RESOLUTION_COMPLETE,
  725. util::itos(getCuid()).c_str(),
  726. hostname.c_str(),
  727. strjoin(addrs.begin(), addrs.end(), ", ").c_str());
  728. }
  729. for(std::vector<std::string>::const_iterator i = addrs.begin(),
  730. eoi = addrs.end(); i != eoi; ++i) {
  731. e_->cacheIPAddress(hostname, *i, port);
  732. }
  733. ipaddr = e_->findCachedIPAddress(hostname, port);
  734. } else {
  735. ipaddr = addrs.front();
  736. if(getLogger()->info()) {
  737. getLogger()->info(MSG_DNS_CACHE_HIT,
  738. util::itos(getCuid()).c_str(), hostname.c_str(),
  739. strjoin(addrs.begin(), addrs.end(), ", ").c_str());
  740. }
  741. }
  742. return ipaddr;
  743. }
  744. // nextCommand is going to be managed by CheckIntegrityEntry which is
  745. // created in side this function. Don't release nextCommand after this
  746. // function call.
  747. void AbstractCommand::prepareForNextAction(Command* nextCommand)
  748. {
  749. SharedHandle<CheckIntegrityEntry> checkEntry;
  750. #ifdef ENABLE_MESSAGE_DIGEST
  751. if(requestGroup_->downloadFinished() &&
  752. getDownloadContext()->isChecksumVerificationNeeded()) {
  753. if(getLogger()->info()) {
  754. getLogger()->info(MSG_HASH_CHECK_NOT_DONE);
  755. }
  756. SharedHandle<ChecksumCheckIntegrityEntry> entry
  757. (new ChecksumCheckIntegrityEntry(requestGroup_, nextCommand));
  758. entry->setRedownload(true);
  759. checkEntry = entry;
  760. } else
  761. #endif // ENABLE_MESSAGE_DIGEST
  762. {
  763. checkEntry.reset
  764. (new StreamCheckIntegrityEntry(requestGroup_, nextCommand));
  765. }
  766. std::vector<Command*>* commands = new std::vector<Command*>();
  767. auto_delete_container<std::vector<Command*> > commandsDel(commands);
  768. requestGroup_->processCheckIntegrityEntry(*commands, checkEntry, e_);
  769. e_->addCommand(*commands);
  770. commands->clear();
  771. e_->setNoWait(true);
  772. }
  773. bool AbstractCommand::checkIfConnectionEstablished
  774. (const SharedHandle<SocketCore>& socket,
  775. const std::string& connectedHostname,
  776. const std::string& connectedAddr,
  777. uint16_t connectedPort)
  778. {
  779. if(socket->isReadable(0)) {
  780. std::string error = socket->getSocketError();
  781. if(!error.empty()) {
  782. // See also InitiateConnectionCommand::executeInternal()
  783. e_->markBadIPAddress(connectedHostname, connectedAddr, connectedPort);
  784. if(!e_->findCachedIPAddress(connectedHostname, connectedPort).empty()) {
  785. if(getLogger()->info()) {
  786. getLogger()->info(MSG_CONNECT_FAILED_AND_RETRY,
  787. util::itos(getCuid()).c_str(),
  788. connectedAddr.c_str(), connectedPort);
  789. }
  790. Command* command =
  791. InitiateConnectionCommandFactory::createInitiateConnectionCommand
  792. (getCuid(), req_, fileEntry_, requestGroup_, e_);
  793. e_->setNoWait(true);
  794. e_->addCommand(command);
  795. return false;
  796. }
  797. e_->removeCachedIPAddress(connectedHostname, connectedPort);
  798. // Don't set error if proxy server is used and its method is GET.
  799. if(resolveProxyMethod(req_->getProtocol()) != V_GET ||
  800. !isProxyRequest(req_->getProtocol(), getOption())) {
  801. e_->getRequestGroupMan()->getOrCreateServerStat
  802. (req_->getHost(), req_->getProtocol())->setError();
  803. }
  804. throw DL_RETRY_EX
  805. (StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()).str());
  806. }
  807. }
  808. return true;
  809. }
  810. const std::string& AbstractCommand::resolveProxyMethod
  811. (const std::string& protocol) const
  812. {
  813. if(getOption()->get(PREF_PROXY_METHOD) == V_TUNNEL ||
  814. Request::PROTO_HTTPS == protocol) {
  815. return V_TUNNEL;
  816. } else {
  817. return V_GET;
  818. }
  819. }
  820. const SharedHandle<Option>& AbstractCommand::getOption() const
  821. {
  822. return requestGroup_->getOption();
  823. }
  824. void AbstractCommand::createSocket()
  825. {
  826. socket_.reset(new SocketCore());
  827. }
  828. size_t AbstractCommand::calculateMinSplitSize() const
  829. {
  830. if(!req_.isNull() && req_->isPipeliningEnabled()) {
  831. return getDownloadContext()->getPieceLength();
  832. } else {
  833. return getOption()->getAsInt(PREF_MIN_SPLIT_SIZE);
  834. }
  835. }
  836. } // namespace aria2