AbstractCommand.cc 29 KB

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