AbstractCommand.cc 30 KB

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