AbstractCommand.cc 30 KB

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