AbstractCommand.cc 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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. throw DL_RETRY_EX(
  283. fmt(MSG_NETWORK_PROBLEM, socket_->getSocketError().c_str()));
  284. }
  285. if (checkPoint_.difference(global::wallclock()) >= timeout_) {
  286. // timeout triggers ServerStat error state.
  287. auto ss = e_->getRequestGroupMan()->getOrCreateServerStat(
  288. req_->getHost(), req_->getProtocol());
  289. ss->setError();
  290. // When DNS query was timeout, req_->getConnectedAddr() is
  291. // empty.
  292. if (!req_->getConnectedAddr().empty()) {
  293. // Purging IP address cache to renew IP address.
  294. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Marking IP address %s as bad",
  295. getCuid(), req_->getConnectedAddr().c_str()));
  296. e_->markBadIPAddress(req_->getConnectedHostname(),
  297. req_->getConnectedAddr(),
  298. req_->getConnectedPort());
  299. }
  300. if (e_->findCachedIPAddress(req_->getConnectedHostname(),
  301. req_->getConnectedPort()).empty()) {
  302. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - All IP addresses were marked bad."
  303. " Removing Entry.",
  304. getCuid()));
  305. e_->removeCachedIPAddress(req_->getConnectedHostname(),
  306. req_->getConnectedPort());
  307. }
  308. throw DL_RETRY_EX2(EX_TIME_OUT, error_code::TIME_OUT);
  309. }
  310. addCommandSelf();
  311. return false;
  312. }
  313. catch (DlAbortEx& err) {
  314. requestGroup_->setLastErrorCode(err.getErrorCode(), err.what());
  315. if (req_) {
  316. A2_LOG_ERROR_EX(
  317. fmt(MSG_DOWNLOAD_ABORTED, getCuid(), req_->getUri().c_str()),
  318. DL_ABORT_EX2(fmt("URI=%s", req_->getCurrentUri().c_str()), err));
  319. fileEntry_->addURIResult(req_->getUri(), err.getErrorCode());
  320. if (err.getErrorCode() == error_code::CANNOT_RESUME) {
  321. requestGroup_->increaseResumeFailureCount();
  322. }
  323. }
  324. else {
  325. A2_LOG_DEBUG_EX(EX_EXCEPTION_CAUGHT, err);
  326. }
  327. onAbort();
  328. tryReserved();
  329. return true;
  330. }
  331. catch (DlRetryEx& err) {
  332. assert(req_);
  333. A2_LOG_INFO_EX(
  334. fmt(MSG_RESTARTING_DOWNLOAD, getCuid(), req_->getUri().c_str()),
  335. DL_RETRY_EX2(fmt("URI=%s", req_->getCurrentUri().c_str()), err));
  336. req_->addTryCount();
  337. req_->resetRedirectCount();
  338. req_->resetUri();
  339. const int maxTries = getOption()->getAsInt(PREF_MAX_TRIES);
  340. bool isAbort = maxTries != 0 && req_->getTryCount() >= maxTries;
  341. if (isAbort) {
  342. A2_LOG_INFO(fmt(MSG_MAX_TRY, getCuid(), req_->getTryCount()));
  343. A2_LOG_ERROR_EX(
  344. fmt(MSG_DOWNLOAD_ABORTED, getCuid(), req_->getUri().c_str()), err);
  345. fileEntry_->addURIResult(req_->getUri(), err.getErrorCode());
  346. requestGroup_->setLastErrorCode(err.getErrorCode(), err.what());
  347. if (err.getErrorCode() == error_code::CANNOT_RESUME) {
  348. requestGroup_->increaseResumeFailureCount();
  349. }
  350. onAbort();
  351. tryReserved();
  352. return true;
  353. }
  354. Timer wakeTime(global::wallclock());
  355. wakeTime.advance(
  356. std::chrono::seconds(getOption()->getAsInt(PREF_RETRY_WAIT)));
  357. req_->setWakeTime(wakeTime);
  358. return prepareForRetry(0);
  359. }
  360. catch (DownloadFailureException& err) {
  361. requestGroup_->setLastErrorCode(err.getErrorCode(), err.what());
  362. if (req_) {
  363. A2_LOG_ERROR_EX(
  364. fmt(MSG_DOWNLOAD_ABORTED, getCuid(), req_->getUri().c_str()),
  365. DL_ABORT_EX2(fmt("URI=%s", req_->getCurrentUri().c_str()), err));
  366. fileEntry_->addURIResult(req_->getUri(), err.getErrorCode());
  367. }
  368. else {
  369. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, err);
  370. }
  371. requestGroup_->setHaltRequested(true);
  372. getDownloadEngine()->setRefreshInterval(std::chrono::milliseconds(0));
  373. return true;
  374. }
  375. }
  376. void AbstractCommand::tryReserved()
  377. {
  378. if (getDownloadContext()->getFileEntries().size() == 1) {
  379. const auto& entry = getDownloadContext()->getFirstFileEntry();
  380. // Don't create new command if currently file length is unknown
  381. // and there are no URI left. Because file length is unknown, we
  382. // can assume that there are no in-flight request object.
  383. if (entry->getLength() == 0 && entry->getRemainingUris().empty()) {
  384. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Not trying next request."
  385. " No reserved/pooled request is remaining and"
  386. " total length is still unknown.",
  387. getCuid()));
  388. return;
  389. }
  390. }
  391. A2_LOG_DEBUG(
  392. fmt("CUID#%" PRId64 " - Trying reserved/pooled request.", getCuid()));
  393. std::vector<std::unique_ptr<Command>> commands;
  394. requestGroup_->createNextCommand(commands, e_, 1);
  395. e_->setNoWait(true);
  396. e_->addCommand(std::move(commands));
  397. }
  398. bool AbstractCommand::prepareForRetry(time_t wait)
  399. {
  400. if (getPieceStorage()) {
  401. getSegmentMan()->cancelSegment(getCuid());
  402. }
  403. if (req_) {
  404. // Reset persistentConnection and maxPipelinedRequest to handle
  405. // the situation where remote server returns Connection: close
  406. // after several pipelined requests.
  407. req_->supportsPersistentConnection(true);
  408. req_->setMaxPipelinedRequest(1);
  409. fileEntry_->poolRequest(req_);
  410. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Pooling request URI=%s", getCuid(),
  411. req_->getUri().c_str()));
  412. if (getSegmentMan()) {
  413. getSegmentMan()->recognizeSegmentFor(fileEntry_);
  414. }
  415. }
  416. auto command =
  417. make_unique<CreateRequestCommand>(getCuid(), requestGroup_, e_);
  418. if (wait == 0) {
  419. e_->setNoWait(true);
  420. }
  421. else {
  422. // We don't use wait so that Command can be executed by
  423. // DownloadEngine::setRefreshInterval(std::chrono::milliseconds(0)).
  424. command->setStatus(Command::STATUS_INACTIVE);
  425. }
  426. e_->addCommand(std::move(command));
  427. return true;
  428. }
  429. void AbstractCommand::onAbort()
  430. {
  431. if (req_) {
  432. fileEntry_->removeIdenticalURI(req_->getUri());
  433. fileEntry_->removeRequest(req_);
  434. }
  435. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Aborting download", getCuid()));
  436. if (!getPieceStorage()) {
  437. return;
  438. }
  439. getSegmentMan()->cancelSegment(getCuid());
  440. // Don't do following process if BitTorrent is involved or files
  441. // in DownloadContext is more than 1. The latter condition is
  442. // limitation of current implementation.
  443. if (getOption()->getAsBool(PREF_ALWAYS_RESUME) || !fileEntry_ ||
  444. getDownloadContext()->getNetStat().getSessionDownloadLength() != 0 ||
  445. requestGroup_->p2pInvolved() ||
  446. getDownloadContext()->getFileEntries().size() != 1) {
  447. return;
  448. }
  449. const int maxTries = getOption()->getAsInt(PREF_MAX_RESUME_FAILURE_TRIES);
  450. if (!(maxTries > 0 && requestGroup_->getResumeFailureCount() >= maxTries) &&
  451. !fileEntry_->emptyRequestUri()) {
  452. return;
  453. }
  454. // Local file exists, but given servers(or at least contacted
  455. // ones) doesn't support resume. Let's restart download from
  456. // scratch.
  457. A2_LOG_NOTICE(fmt(_("CUID#%" PRId64 " - Failed to resume download."
  458. " Download from scratch."),
  459. getCuid()));
  460. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Gathering URIs that has CANNOT_RESUME"
  461. " error",
  462. getCuid()));
  463. // Set PREF_ALWAYS_RESUME to A2_V_TRUE to avoid repeating this
  464. // process.
  465. getOption()->put(PREF_ALWAYS_RESUME, A2_V_TRUE);
  466. std::deque<URIResult> res;
  467. fileEntry_->extractURIResult(res, error_code::CANNOT_RESUME);
  468. if (res.empty()) {
  469. return;
  470. }
  471. getSegmentMan()->cancelAllSegments();
  472. getSegmentMan()->eraseSegmentWrittenLengthMemo();
  473. getPieceStorage()->markPiecesDone(0);
  474. std::vector<std::string> uris;
  475. uris.reserve(res.size());
  476. std::transform(std::begin(res), std::end(res), std::back_inserter(uris),
  477. std::mem_fn(&URIResult::getURI));
  478. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - %lu URIs found.", getCuid(),
  479. static_cast<unsigned long int>(uris.size())));
  480. fileEntry_->addUris(std::begin(uris), std::end(uris));
  481. getSegmentMan()->recognizeSegmentFor(fileEntry_);
  482. }
  483. void AbstractCommand::disableReadCheckSocket()
  484. {
  485. if (!checkSocketIsReadable_) {
  486. return;
  487. }
  488. e_->deleteSocketForReadCheck(readCheckTarget_, this);
  489. checkSocketIsReadable_ = false;
  490. readCheckTarget_.reset();
  491. }
  492. void AbstractCommand::setReadCheckSocket(
  493. const std::shared_ptr<SocketCore>& socket)
  494. {
  495. if (!socket->isOpen()) {
  496. disableReadCheckSocket();
  497. return;
  498. }
  499. if (checkSocketIsReadable_) {
  500. if (*readCheckTarget_ != *socket) {
  501. e_->deleteSocketForReadCheck(readCheckTarget_, this);
  502. e_->addSocketForReadCheck(socket, this);
  503. readCheckTarget_ = socket;
  504. }
  505. return;
  506. }
  507. e_->addSocketForReadCheck(socket, this);
  508. checkSocketIsReadable_ = true;
  509. readCheckTarget_ = socket;
  510. }
  511. void AbstractCommand::setReadCheckSocketIf(
  512. const std::shared_ptr<SocketCore>& socket, bool pred)
  513. {
  514. if (pred) {
  515. setReadCheckSocket(socket);
  516. return;
  517. }
  518. disableReadCheckSocket();
  519. }
  520. void AbstractCommand::disableWriteCheckSocket()
  521. {
  522. if (!checkSocketIsWritable_) {
  523. return;
  524. }
  525. e_->deleteSocketForWriteCheck(writeCheckTarget_, this);
  526. checkSocketIsWritable_ = false;
  527. writeCheckTarget_.reset();
  528. }
  529. void AbstractCommand::setWriteCheckSocket(
  530. const std::shared_ptr<SocketCore>& socket)
  531. {
  532. if (!socket->isOpen()) {
  533. disableWriteCheckSocket();
  534. return;
  535. }
  536. if (checkSocketIsWritable_) {
  537. if (*writeCheckTarget_ != *socket) {
  538. e_->deleteSocketForWriteCheck(writeCheckTarget_, this);
  539. e_->addSocketForWriteCheck(socket, this);
  540. writeCheckTarget_ = socket;
  541. }
  542. return;
  543. }
  544. e_->addSocketForWriteCheck(socket, this);
  545. checkSocketIsWritable_ = true;
  546. writeCheckTarget_ = socket;
  547. }
  548. void AbstractCommand::setWriteCheckSocketIf(
  549. const std::shared_ptr<SocketCore>& socket, bool pred)
  550. {
  551. if (pred) {
  552. setWriteCheckSocket(socket);
  553. return;
  554. }
  555. disableWriteCheckSocket();
  556. }
  557. void AbstractCommand::swapSocket(std::shared_ptr<SocketCore>& socket)
  558. {
  559. disableReadCheckSocket();
  560. disableWriteCheckSocket();
  561. socket_.swap(socket);
  562. }
  563. namespace {
  564. // Constructs proxy URI, merging username and password if they are
  565. // defined.
  566. std::string makeProxyUri(PrefPtr proxyPref, PrefPtr proxyUser,
  567. PrefPtr proxyPasswd, const Option* option)
  568. {
  569. uri::UriStruct us;
  570. if (!uri::parse(us, option->get(proxyPref))) {
  571. return "";
  572. }
  573. if (option->defined(proxyUser)) {
  574. us.username = option->get(proxyUser);
  575. }
  576. if (option->defined(proxyPasswd)) {
  577. us.password = option->get(proxyPasswd);
  578. us.hasPassword = true;
  579. }
  580. return uri::construct(us);
  581. }
  582. } // namespace
  583. namespace {
  584. // Returns proxy option value for the given protocol.
  585. std::string getProxyOptionFor(PrefPtr proxyPref, PrefPtr proxyUser,
  586. PrefPtr proxyPasswd, const Option* option)
  587. {
  588. std::string uri = makeProxyUri(proxyPref, proxyUser, proxyPasswd, option);
  589. if (uri.empty()) {
  590. return makeProxyUri(PREF_ALL_PROXY, PREF_ALL_PROXY_USER,
  591. PREF_ALL_PROXY_PASSWD, option);
  592. }
  593. return uri;
  594. }
  595. } // namespace
  596. // Returns proxy URI for given protocol. If no proxy URI is defined,
  597. // then returns an empty string.
  598. std::string getProxyUri(const std::string& protocol, const Option* option)
  599. {
  600. if (protocol == "http") {
  601. return getProxyOptionFor(PREF_HTTP_PROXY, PREF_HTTP_PROXY_USER,
  602. PREF_HTTP_PROXY_PASSWD, option);
  603. }
  604. if (protocol == "https") {
  605. return getProxyOptionFor(PREF_HTTPS_PROXY, PREF_HTTPS_PROXY_USER,
  606. PREF_HTTPS_PROXY_PASSWD, option);
  607. }
  608. if (protocol == "ftp" || protocol == "sftp") {
  609. return getProxyOptionFor(PREF_FTP_PROXY, PREF_FTP_PROXY_USER,
  610. PREF_FTP_PROXY_PASSWD, option);
  611. }
  612. return A2STR::NIL;
  613. }
  614. namespace {
  615. // Returns true if proxy is defined for the given protocol. Otherwise
  616. // returns false.
  617. bool isProxyRequest(const std::string& protocol,
  618. const std::shared_ptr<Option>& option)
  619. {
  620. std::string proxyUri = getProxyUri(protocol, option.get());
  621. return !proxyUri.empty();
  622. }
  623. } // namespace
  624. namespace {
  625. bool inNoProxy(const std::shared_ptr<Request>& req, const std::string& noProxy)
  626. {
  627. std::vector<Scip> entries;
  628. util::splitIter(std::begin(noProxy), std::end(noProxy),
  629. std::back_inserter(entries), ',', true);
  630. if (entries.empty()) {
  631. return false;
  632. }
  633. for (const auto& e : entries) {
  634. const auto slashpos = std::find(e.first, e.second, '/');
  635. if (slashpos == e.second) {
  636. if (util::noProxyDomainMatch(req->getHost(),
  637. std::string(e.first, e.second))) {
  638. return true;
  639. }
  640. continue;
  641. }
  642. // TODO We don't resolve hostname here. More complete
  643. // implementation is that we should first resolve
  644. // hostname(which may result in several IP addresses) and
  645. // evaluates against all of them
  646. std::string ip(e.first, slashpos);
  647. uint32_t bits;
  648. if (!util::parseUIntNoThrow(bits, std::string(slashpos + 1, e.second))) {
  649. continue;
  650. }
  651. if (util::inSameCidrBlock(ip, req->getHost(), bits)) {
  652. return true;
  653. }
  654. }
  655. return false;
  656. }
  657. } // namespace
  658. bool AbstractCommand::isProxyDefined() const
  659. {
  660. return isProxyRequest(req_->getProtocol(), getOption()) &&
  661. !inNoProxy(req_, getOption()->get(PREF_NO_PROXY));
  662. }
  663. std::shared_ptr<Request> AbstractCommand::createProxyRequest() const
  664. {
  665. std::shared_ptr<Request> proxyRequest;
  666. if (inNoProxy(req_, getOption()->get(PREF_NO_PROXY))) {
  667. return proxyRequest;
  668. }
  669. std::string proxy = getProxyUri(req_->getProtocol(), getOption().get());
  670. if (!proxy.empty()) {
  671. proxyRequest = std::make_shared<Request>();
  672. if (proxyRequest->setUri(proxy)) {
  673. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Using proxy", getCuid()));
  674. }
  675. else {
  676. A2_LOG_DEBUG(
  677. fmt("CUID#%" PRId64 " - Failed to parse proxy string", getCuid()));
  678. proxyRequest.reset();
  679. }
  680. }
  681. return proxyRequest;
  682. }
  683. std::string AbstractCommand::resolveHostname(std::vector<std::string>& addrs,
  684. const std::string& hostname,
  685. uint16_t port)
  686. {
  687. if (util::isNumericHost(hostname)) {
  688. addrs.push_back(hostname);
  689. return hostname;
  690. }
  691. e_->findAllCachedIPAddresses(std::back_inserter(addrs), hostname, port);
  692. if (!addrs.empty()) {
  693. auto ipaddr = addrs.front();
  694. A2_LOG_INFO(fmt(MSG_DNS_CACHE_HIT, getCuid(), hostname.c_str(),
  695. strjoin(std::begin(addrs), std::end(addrs), ", ").c_str()));
  696. return ipaddr;
  697. }
  698. std::string ipaddr;
  699. #ifdef ENABLE_ASYNC_DNS
  700. if (getOption()->getAsBool(PREF_ASYNC_DNS)) {
  701. if (!asyncNameResolverMan_->started()) {
  702. asyncNameResolverMan_->startAsync(hostname, e_, this);
  703. }
  704. switch (asyncNameResolverMan_->getStatus()) {
  705. case -1:
  706. if (!isProxyRequest(req_->getProtocol(), getOption())) {
  707. e_->getRequestGroupMan()
  708. ->getOrCreateServerStat(req_->getHost(), req_->getProtocol())
  709. ->setError();
  710. }
  711. throw DL_ABORT_EX2(fmt(MSG_NAME_RESOLUTION_FAILED, getCuid(),
  712. hostname.c_str(),
  713. asyncNameResolverMan_->getLastError().c_str()),
  714. error_code::NAME_RESOLVE_ERROR);
  715. case 0:
  716. return A2STR::NIL;
  717. case 1:
  718. asyncNameResolverMan_->getResolvedAddress(addrs);
  719. if (addrs.empty()) {
  720. throw DL_ABORT_EX2(fmt(MSG_NAME_RESOLUTION_FAILED, getCuid(),
  721. hostname.c_str(), "No address returned"),
  722. error_code::NAME_RESOLVE_ERROR);
  723. }
  724. break;
  725. }
  726. }
  727. else
  728. #endif // ENABLE_ASYNC_DNS
  729. {
  730. NameResolver res;
  731. res.setSocktype(SOCK_STREAM);
  732. if (e_->getOption()->getAsBool(PREF_DISABLE_IPV6)) {
  733. res.setFamily(AF_INET);
  734. }
  735. res.resolve(addrs, hostname);
  736. }
  737. A2_LOG_INFO(fmt(MSG_NAME_RESOLUTION_COMPLETE, getCuid(), hostname.c_str(),
  738. strjoin(std::begin(addrs), std::end(addrs), ", ").c_str()));
  739. for (const auto& addr : addrs) {
  740. e_->cacheIPAddress(hostname, addr, port);
  741. }
  742. ipaddr = e_->findCachedIPAddress(hostname, port);
  743. return ipaddr;
  744. }
  745. void AbstractCommand::prepareForNextAction(
  746. std::unique_ptr<CheckIntegrityEntry> checkEntry)
  747. {
  748. std::vector<std::unique_ptr<Command>> commands;
  749. requestGroup_->processCheckIntegrityEntry(commands, std::move(checkEntry),
  750. e_);
  751. e_->addCommand(std::move(commands));
  752. e_->setNoWait(true);
  753. }
  754. bool AbstractCommand::checkIfConnectionEstablished(
  755. const std::shared_ptr<SocketCore>& socket,
  756. const std::string& connectedHostname, const std::string& connectedAddr,
  757. uint16_t connectedPort)
  758. {
  759. std::string error = socket->getSocketError();
  760. if (error.empty()) {
  761. return true;
  762. }
  763. // See also InitiateConnectionCommand::executeInternal()
  764. e_->markBadIPAddress(connectedHostname, connectedAddr, connectedPort);
  765. if (e_->findCachedIPAddress(connectedHostname, connectedPort).empty()) {
  766. e_->removeCachedIPAddress(connectedHostname, connectedPort);
  767. // Don't set error if proxy server is used and its method is GET.
  768. if (resolveProxyMethod(req_->getProtocol()) != V_GET ||
  769. !isProxyRequest(req_->getProtocol(), getOption())) {
  770. e_->getRequestGroupMan()
  771. ->getOrCreateServerStat(req_->getHost(), req_->getProtocol())
  772. ->setError();
  773. }
  774. throw DL_RETRY_EX(fmt(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()));
  775. }
  776. A2_LOG_INFO(fmt(MSG_CONNECT_FAILED_AND_RETRY, getCuid(),
  777. connectedAddr.c_str(), connectedPort));
  778. e_->setNoWait(true);
  779. e_->addCommand(
  780. InitiateConnectionCommandFactory::createInitiateConnectionCommand(
  781. getCuid(), req_, fileEntry_, requestGroup_, e_));
  782. return false;
  783. }
  784. const std::string&
  785. AbstractCommand::resolveProxyMethod(const std::string& protocol) const
  786. {
  787. if (getOption()->get(PREF_PROXY_METHOD) == V_TUNNEL || protocol == "https" ||
  788. protocol == "sftp") {
  789. return V_TUNNEL;
  790. }
  791. return V_GET;
  792. }
  793. const std::shared_ptr<Option>& AbstractCommand::getOption() const
  794. {
  795. return requestGroup_->getOption();
  796. }
  797. void AbstractCommand::createSocket()
  798. {
  799. socket_ = std::make_shared<SocketCore>();
  800. }
  801. int32_t AbstractCommand::calculateMinSplitSize() const
  802. {
  803. if (req_ && req_->isPipeliningEnabled()) {
  804. return getDownloadContext()->getPieceLength();
  805. }
  806. return getOption()->getAsInt(PREF_MIN_SPLIT_SIZE);
  807. }
  808. void AbstractCommand::setRequest(const std::shared_ptr<Request>& request)
  809. {
  810. req_ = request;
  811. }
  812. void AbstractCommand::resetRequest() { req_.reset(); }
  813. void AbstractCommand::setFileEntry(const std::shared_ptr<FileEntry>& fileEntry)
  814. {
  815. fileEntry_ = fileEntry;
  816. }
  817. void AbstractCommand::setSocket(const std::shared_ptr<SocketCore>& s)
  818. {
  819. socket_ = s;
  820. }
  821. const std::shared_ptr<DownloadContext>&
  822. AbstractCommand::getDownloadContext() const
  823. {
  824. return requestGroup_->getDownloadContext();
  825. }
  826. const std::shared_ptr<SegmentMan>& AbstractCommand::getSegmentMan() const
  827. {
  828. return requestGroup_->getSegmentMan();
  829. }
  830. const std::shared_ptr<PieceStorage>& AbstractCommand::getPieceStorage() const
  831. {
  832. return requestGroup_->getPieceStorage();
  833. }
  834. void AbstractCommand::checkSocketRecvBuffer()
  835. {
  836. if (socketRecvBuffer_->bufferEmpty() &&
  837. socket_->getRecvBufferedLength() == 0) {
  838. return;
  839. }
  840. setStatus(Command::STATUS_ONESHOT_REALTIME);
  841. e_->setNoWait(true);
  842. }
  843. void AbstractCommand::addCommandSelf()
  844. {
  845. e_->addCommand(std::unique_ptr<Command>(this));
  846. }
  847. } // namespace aria2