AbstractCommand.cc 30 KB

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