AbstractCommand.cc 30 KB

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