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