DefaultBtInteractive.cc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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 "DefaultBtInteractive.h"
  36. #include <cstring>
  37. #include <vector>
  38. #include "prefs.h"
  39. #include "message.h"
  40. #include "BtHandshakeMessage.h"
  41. #include "util.h"
  42. #include "BtKeepAliveMessage.h"
  43. #include "BtChokeMessage.h"
  44. #include "BtUnchokeMessage.h"
  45. #include "BtRequestMessage.h"
  46. #include "BtPieceMessage.h"
  47. #include "BtPortMessage.h"
  48. #include "BtInterestedMessage.h"
  49. #include "BtNotInterestedMessage.h"
  50. #include "BtHaveMessage.h"
  51. #include "BtHaveAllMessage.h"
  52. #include "BtBitfieldMessage.h"
  53. #include "BtHaveNoneMessage.h"
  54. #include "BtAllowedFastMessage.h"
  55. #include "DlAbortEx.h"
  56. #include "BtExtendedMessage.h"
  57. #include "HandshakeExtensionMessage.h"
  58. #include "UTPexExtensionMessage.h"
  59. #include "DefaultExtensionMessageFactory.h"
  60. #include "ExtensionMessageRegistry.h"
  61. #include "DHTNode.h"
  62. #include "Peer.h"
  63. #include "Piece.h"
  64. #include "DownloadContext.h"
  65. #include "PieceStorage.h"
  66. #include "PeerStorage.h"
  67. #include "BtRuntime.h"
  68. #include "BtMessageReceiver.h"
  69. #include "BtMessageDispatcher.h"
  70. #include "BtMessageFactory.h"
  71. #include "BtRequestFactory.h"
  72. #include "PeerConnection.h"
  73. #include "Logger.h"
  74. #include "LogFactory.h"
  75. #include "fmt.h"
  76. #include "RequestGroup.h"
  77. #include "RequestGroupMan.h"
  78. #include "bittorrent_helper.h"
  79. #include "UTMetadataRequestFactory.h"
  80. #include "UTMetadataRequestTracker.h"
  81. #include "wallclock.h"
  82. namespace aria2 {
  83. DefaultBtInteractive::DefaultBtInteractive(
  84. const std::shared_ptr<DownloadContext>& downloadContext,
  85. const std::shared_ptr<Peer>& peer)
  86. : cuid_(0),
  87. downloadContext_(downloadContext),
  88. peer_(peer),
  89. metadataGetMode_(false),
  90. localNode_(nullptr),
  91. lastHaveIndex_(0),
  92. allowedFastSetSize_(10),
  93. keepAliveTimer_(global::wallclock()),
  94. floodingTimer_(global::wallclock()),
  95. inactiveTimer_(global::wallclock()),
  96. pexTimer_(global::wallclock()),
  97. perSecTimer_(global::wallclock()),
  98. keepAliveInterval_(120),
  99. utPexEnabled_(false),
  100. dhtEnabled_(false),
  101. numReceivedMessage_(0),
  102. maxOutstandingRequest_(DEFAULT_MAX_OUTSTANDING_REQUEST),
  103. requestGroupMan_(nullptr),
  104. tcpPort_(0)
  105. {
  106. }
  107. DefaultBtInteractive::~DefaultBtInteractive() = default;
  108. void DefaultBtInteractive::initiateHandshake()
  109. {
  110. dispatcher_->addMessageToQueue(messageFactory_->createHandshakeMessage(
  111. bittorrent::getInfoHash(downloadContext_),
  112. bittorrent::getStaticPeerId()));
  113. dispatcher_->sendMessages();
  114. }
  115. std::unique_ptr<BtHandshakeMessage>
  116. DefaultBtInteractive::receiveHandshake(bool quickReply)
  117. {
  118. auto message = btMessageReceiver_->receiveHandshake(quickReply);
  119. if (!message) {
  120. return nullptr;
  121. }
  122. if (memcmp(message->getPeerId(), bittorrent::getStaticPeerId(),
  123. PEER_ID_LENGTH) == 0) {
  124. throw DL_ABORT_EX(
  125. fmt("CUID#%" PRId64 " - Drop connection from the same Peer ID", cuid_));
  126. }
  127. for (auto& peer : peerStorage_->getUsedPeers()) {
  128. if (peer->isActive() &&
  129. memcmp(peer->getPeerId(), message->getPeerId(), PEER_ID_LENGTH) == 0) {
  130. throw DL_ABORT_EX(
  131. fmt("CUID#%" PRId64 " - Same Peer ID has been already seen.", cuid_));
  132. }
  133. }
  134. peer_->setPeerId(message->getPeerId());
  135. if (message->isFastExtensionSupported()) {
  136. peer_->setFastExtensionEnabled(true);
  137. A2_LOG_INFO(fmt(MSG_FAST_EXTENSION_ENABLED, cuid_));
  138. }
  139. if (message->isExtendedMessagingEnabled()) {
  140. peer_->setExtendedMessagingEnabled(true);
  141. if (!utPexEnabled_) {
  142. extensionMessageRegistry_->removeExtension(
  143. ExtensionMessageRegistry::UT_PEX);
  144. }
  145. A2_LOG_INFO(fmt(MSG_EXTENDED_MESSAGING_ENABLED, cuid_));
  146. }
  147. if (message->isDHTEnabled()) {
  148. peer_->setDHTEnabled(true);
  149. A2_LOG_INFO(fmt(MSG_DHT_ENABLED_PEER, cuid_));
  150. }
  151. A2_LOG_INFO(fmt(MSG_RECEIVE_PEER_MESSAGE, cuid_,
  152. peer_->getIPAddress().c_str(), peer_->getPort(),
  153. message->toString().c_str()));
  154. return message;
  155. }
  156. std::unique_ptr<BtHandshakeMessage>
  157. DefaultBtInteractive::receiveAndSendHandshake()
  158. {
  159. return receiveHandshake(true);
  160. }
  161. void DefaultBtInteractive::doPostHandshakeProcessing()
  162. {
  163. // Set time 0 to haveTimer to cache http/ftp download piece completion
  164. keepAliveTimer_ = global::wallclock();
  165. floodingTimer_ = global::wallclock();
  166. pexTimer_ = Timer::zero();
  167. if (peer_->isExtendedMessagingEnabled()) {
  168. addHandshakeExtendedMessageToQueue();
  169. }
  170. if (!metadataGetMode_) {
  171. addBitfieldMessageToQueue();
  172. }
  173. if (peer_->isDHTEnabled() && dhtEnabled_) {
  174. addPortMessageToQueue();
  175. }
  176. if (!metadataGetMode_) {
  177. addAllowedFastMessageToQueue();
  178. }
  179. sendPendingMessage();
  180. }
  181. void DefaultBtInteractive::addPortMessageToQueue()
  182. {
  183. dispatcher_->addMessageToQueue(
  184. messageFactory_->createPortMessage(localNode_->getPort()));
  185. }
  186. void DefaultBtInteractive::addHandshakeExtendedMessageToQueue()
  187. {
  188. auto m = make_unique<HandshakeExtensionMessage>();
  189. m->setClientVersion("aria2/" PACKAGE_VERSION);
  190. m->setTCPPort(tcpPort_);
  191. m->setExtensions(extensionMessageRegistry_->getExtensions());
  192. auto attrs = bittorrent::getTorrentAttrs(downloadContext_);
  193. if (!attrs->metadata.empty()) {
  194. m->setMetadataSize(attrs->metadataSize);
  195. }
  196. dispatcher_->addMessageToQueue(
  197. messageFactory_->createBtExtendedMessage(std::move(m)));
  198. }
  199. void DefaultBtInteractive::addBitfieldMessageToQueue()
  200. {
  201. if (peer_->isFastExtensionEnabled()) {
  202. if (pieceStorage_->allDownloadFinished()) {
  203. dispatcher_->addMessageToQueue(messageFactory_->createHaveAllMessage());
  204. }
  205. else if (pieceStorage_->getCompletedLength() > 0) {
  206. dispatcher_->addMessageToQueue(messageFactory_->createBitfieldMessage());
  207. }
  208. else {
  209. dispatcher_->addMessageToQueue(messageFactory_->createHaveNoneMessage());
  210. }
  211. }
  212. else {
  213. if (pieceStorage_->getCompletedLength() > 0) {
  214. dispatcher_->addMessageToQueue(messageFactory_->createBitfieldMessage());
  215. }
  216. }
  217. }
  218. void DefaultBtInteractive::addAllowedFastMessageToQueue()
  219. {
  220. if (peer_->isFastExtensionEnabled()) {
  221. auto fastSet = bittorrent::computeFastSet(
  222. peer_->getIPAddress(), downloadContext_->getNumPieces(),
  223. bittorrent::getInfoHash(downloadContext_), allowedFastSetSize_);
  224. for (std::vector<size_t>::const_iterator itr = fastSet.begin(),
  225. eoi = fastSet.end();
  226. itr != eoi; ++itr) {
  227. dispatcher_->addMessageToQueue(
  228. messageFactory_->createAllowedFastMessage(*itr));
  229. }
  230. }
  231. }
  232. void DefaultBtInteractive::decideChoking()
  233. {
  234. if (peer_->shouldBeChoking()) {
  235. if (!peer_->amChoking()) {
  236. peer_->amChoking(true);
  237. dispatcher_->doChokingAction();
  238. dispatcher_->addMessageToQueue(messageFactory_->createChokeMessage());
  239. }
  240. }
  241. else {
  242. if (peer_->amChoking()) {
  243. peer_->amChoking(false);
  244. dispatcher_->addMessageToQueue(messageFactory_->createUnchokeMessage());
  245. }
  246. }
  247. }
  248. void DefaultBtInteractive::checkHave()
  249. {
  250. std::vector<size_t> haveIndexes;
  251. lastHaveIndex_ = pieceStorage_->getAdvertisedPieceIndexes(haveIndexes, cuid_,
  252. lastHaveIndex_);
  253. // Use bitfield message if it is equal to or less than the total
  254. // size of have messages.
  255. if (5 + pieceStorage_->getBitfieldLength() <= haveIndexes.size() * 9) {
  256. if (peer_->isFastExtensionEnabled() &&
  257. pieceStorage_->allDownloadFinished()) {
  258. dispatcher_->addMessageToQueue(messageFactory_->createHaveAllMessage());
  259. return;
  260. }
  261. dispatcher_->addMessageToQueue(messageFactory_->createBitfieldMessage());
  262. return;
  263. }
  264. for (auto idx : haveIndexes) {
  265. dispatcher_->addMessageToQueue(messageFactory_->createHaveMessage(idx));
  266. }
  267. }
  268. void DefaultBtInteractive::sendKeepAlive()
  269. {
  270. if (keepAliveTimer_.difference(global::wallclock()) >= keepAliveInterval_) {
  271. dispatcher_->addMessageToQueue(messageFactory_->createKeepAliveMessage());
  272. dispatcher_->sendMessages();
  273. keepAliveTimer_ = global::wallclock();
  274. }
  275. }
  276. size_t DefaultBtInteractive::receiveMessages()
  277. {
  278. size_t countOldOutstandingRequest = dispatcher_->countOutstandingRequest();
  279. size_t msgcount = 0;
  280. while (1) {
  281. if (requestGroupMan_->doesOverallDownloadSpeedExceed() ||
  282. downloadContext_->getOwnerRequestGroup()->doesDownloadSpeedExceed()) {
  283. break;
  284. }
  285. auto message = btMessageReceiver_->receiveMessage();
  286. if (!message) {
  287. break;
  288. }
  289. ++msgcount;
  290. A2_LOG_INFO(fmt(MSG_RECEIVE_PEER_MESSAGE, cuid_,
  291. peer_->getIPAddress().c_str(), peer_->getPort(),
  292. message->toString().c_str()));
  293. message->doReceivedAction();
  294. switch (message->getId()) {
  295. case BtChokeMessage::ID:
  296. if (!peer_->peerChoking()) {
  297. floodingStat_.incChokeUnchokeCount();
  298. }
  299. break;
  300. case BtUnchokeMessage::ID:
  301. if (peer_->peerChoking()) {
  302. floodingStat_.incChokeUnchokeCount();
  303. }
  304. break;
  305. case BtRequestMessage::ID:
  306. case BtPieceMessage::ID:
  307. inactiveTimer_ = global::wallclock();
  308. break;
  309. case BtKeepAliveMessage::ID:
  310. floodingStat_.incKeepAliveCount();
  311. break;
  312. }
  313. }
  314. if (!pieceStorage_->isEndGame() &&
  315. countOldOutstandingRequest > dispatcher_->countOutstandingRequest() &&
  316. (countOldOutstandingRequest - dispatcher_->countOutstandingRequest()) *
  317. 4 >=
  318. maxOutstandingRequest_) {
  319. maxOutstandingRequest_ = std::min((size_t)UB_MAX_OUTSTANDING_REQUEST,
  320. maxOutstandingRequest_ * 2);
  321. }
  322. return msgcount;
  323. }
  324. void DefaultBtInteractive::decideInterest()
  325. {
  326. if (pieceStorage_->hasMissingPiece(peer_)) {
  327. if (!peer_->amInterested()) {
  328. A2_LOG_DEBUG(fmt(MSG_PEER_INTERESTED, cuid_));
  329. peer_->amInterested(true);
  330. dispatcher_->addMessageToQueue(
  331. messageFactory_->createInterestedMessage());
  332. }
  333. }
  334. else {
  335. if (peer_->amInterested()) {
  336. A2_LOG_DEBUG(fmt(MSG_PEER_NOT_INTERESTED, cuid_));
  337. peer_->amInterested(false);
  338. dispatcher_->addMessageToQueue(
  339. messageFactory_->createNotInterestedMessage());
  340. }
  341. }
  342. }
  343. void DefaultBtInteractive::fillPiece(size_t maxMissingBlock)
  344. {
  345. if (pieceStorage_->hasMissingPiece(peer_)) {
  346. size_t numMissingBlock = btRequestFactory_->countMissingBlock();
  347. if (numMissingBlock >= maxMissingBlock) {
  348. return;
  349. }
  350. size_t diffMissingBlock = maxMissingBlock - numMissingBlock;
  351. std::vector<std::shared_ptr<Piece>> pieces;
  352. if (peer_->peerChoking()) {
  353. if (peer_->isFastExtensionEnabled()) {
  354. if (pieceStorage_->isEndGame()) {
  355. pieceStorage_->getMissingFastPiece(
  356. pieces, diffMissingBlock, peer_,
  357. btRequestFactory_->getTargetPieceIndexes(), cuid_);
  358. }
  359. else {
  360. pieces.reserve(diffMissingBlock);
  361. pieceStorage_->getMissingFastPiece(pieces, diffMissingBlock, peer_,
  362. cuid_);
  363. }
  364. }
  365. }
  366. else {
  367. if (pieceStorage_->isEndGame()) {
  368. pieceStorage_->getMissingPiece(
  369. pieces, diffMissingBlock, peer_,
  370. btRequestFactory_->getTargetPieceIndexes(), cuid_);
  371. }
  372. else {
  373. pieces.reserve(diffMissingBlock);
  374. pieceStorage_->getMissingPiece(pieces, diffMissingBlock, peer_, cuid_);
  375. }
  376. }
  377. for (std::vector<std::shared_ptr<Piece>>::const_iterator i = pieces.begin(),
  378. eoi = pieces.end();
  379. i != eoi; ++i) {
  380. btRequestFactory_->addTargetPiece(*i);
  381. }
  382. }
  383. }
  384. void DefaultBtInteractive::addRequests()
  385. {
  386. if (!pieceStorage_->isEndGame() && !pieceStorage_->hasMissingUnusedPiece()) {
  387. pieceStorage_->enterEndGame();
  388. }
  389. fillPiece(maxOutstandingRequest_);
  390. size_t reqNumToCreate =
  391. maxOutstandingRequest_ <= dispatcher_->countOutstandingRequest()
  392. ? 0
  393. : maxOutstandingRequest_ - dispatcher_->countOutstandingRequest();
  394. if (reqNumToCreate > 0) {
  395. auto requests = btRequestFactory_->createRequestMessages(
  396. reqNumToCreate, pieceStorage_->isEndGame());
  397. for (auto& i : requests) {
  398. dispatcher_->addMessageToQueue(std::move(i));
  399. }
  400. }
  401. }
  402. void DefaultBtInteractive::cancelAllPiece()
  403. {
  404. btRequestFactory_->removeAllTargetPiece();
  405. if (metadataGetMode_ && downloadContext_->getTotalLength() > 0) {
  406. std::vector<size_t> metadataRequests =
  407. utMetadataRequestTracker_->getAllTrackedIndex();
  408. for (std::vector<size_t>::const_iterator i = metadataRequests.begin(),
  409. eoi = metadataRequests.end();
  410. i != eoi; ++i) {
  411. A2_LOG_DEBUG(
  412. fmt("Cancel metadata: piece=%lu", static_cast<unsigned long>(*i)));
  413. pieceStorage_->cancelPiece(pieceStorage_->getPiece(*i), cuid_);
  414. }
  415. }
  416. }
  417. void DefaultBtInteractive::sendPendingMessage() { dispatcher_->sendMessages(); }
  418. namespace {
  419. constexpr auto FLOODING_CHECK_INTERVAL = 5_s;
  420. } // namespace
  421. void DefaultBtInteractive::detectMessageFlooding()
  422. {
  423. if (floodingTimer_.difference(global::wallclock()) >=
  424. FLOODING_CHECK_INTERVAL) {
  425. if (floodingStat_.getChokeUnchokeCount() >= 2 ||
  426. floodingStat_.getKeepAliveCount() >= 2) {
  427. throw DL_ABORT_EX(EX_FLOODING_DETECTED);
  428. }
  429. else {
  430. floodingStat_.reset();
  431. }
  432. floodingTimer_ = global::wallclock();
  433. }
  434. }
  435. void DefaultBtInteractive::checkActiveInteraction()
  436. {
  437. auto inactiveTime = inactiveTimer_.difference(global::wallclock());
  438. // To allow aria2 to accept mutially interested peer, disconnect uninterested
  439. // peer.
  440. {
  441. const time_t interval = 30;
  442. if (!peer_->amInterested() && !peer_->peerInterested() &&
  443. inactiveTime >= std::chrono::seconds(interval)) {
  444. peer_->setDisconnectedGracefully(true);
  445. // TODO change the message
  446. throw DL_ABORT_EX(
  447. fmt("Disconnect peer because we are not interested each other"
  448. " after %ld second(s).",
  449. static_cast<long int>(interval)));
  450. }
  451. }
  452. // Since the peers which are *just* connected and do nothing to improve
  453. // mutual download progress are completely waste of resources, those peers
  454. // are disconnected in a certain time period.
  455. {
  456. const time_t interval = 60;
  457. if (inactiveTime >= std::chrono::seconds(interval)) {
  458. peer_->setDisconnectedGracefully(true);
  459. throw DL_ABORT_EX(
  460. fmt(EX_DROP_INACTIVE_CONNECTION, static_cast<long int>(interval)));
  461. }
  462. }
  463. // If both of us are seeders, drop connection.
  464. if (peer_->isSeeder() && pieceStorage_->downloadFinished()) {
  465. throw DL_ABORT_EX(MSG_GOOD_BYE_SEEDER);
  466. }
  467. }
  468. void DefaultBtInteractive::addPeerExchangeMessage()
  469. {
  470. if (pexTimer_.difference(global::wallclock()) >=
  471. UTPexExtensionMessage::DEFAULT_INTERVAL) {
  472. auto m = make_unique<UTPexExtensionMessage>(
  473. peer_->getExtensionMessageID(ExtensionMessageRegistry::UT_PEX));
  474. auto& usedPeers = peerStorage_->getUsedPeers();
  475. for (auto i = std::begin(usedPeers), eoi = std::end(usedPeers);
  476. i != eoi && !m->freshPeersAreFull(); ++i) {
  477. if ((*i)->isActive() && peer_->getIPAddress() != (*i)->getIPAddress()) {
  478. m->addFreshPeer(*i);
  479. }
  480. }
  481. auto& droppedPeers = peerStorage_->getDroppedPeers();
  482. for (auto i = std::begin(droppedPeers), eoi = std::end(droppedPeers);
  483. i != eoi && !m->droppedPeersAreFull(); ++i) {
  484. if (peer_->getIPAddress() != (*i)->getIPAddress()) {
  485. m->addDroppedPeer(*i);
  486. }
  487. }
  488. dispatcher_->addMessageToQueue(
  489. messageFactory_->createBtExtendedMessage(std::move(m)));
  490. pexTimer_ = global::wallclock();
  491. }
  492. }
  493. void DefaultBtInteractive::doInteractionProcessing()
  494. {
  495. if (metadataGetMode_) {
  496. sendKeepAlive();
  497. numReceivedMessage_ = receiveMessages();
  498. // PieceStorage is re-initialized with metadata_size in
  499. // HandshakeExtensionMessage::doReceivedAction().
  500. pieceStorage_ = downloadContext_->getOwnerRequestGroup()->getPieceStorage();
  501. if (peer_->getExtensionMessageID(ExtensionMessageRegistry::UT_METADATA) &&
  502. downloadContext_->getTotalLength() > 0) {
  503. size_t num = utMetadataRequestTracker_->avail();
  504. if (num > 0) {
  505. auto requests =
  506. utMetadataRequestFactory_->create(num, pieceStorage_.get());
  507. for (auto& i : requests) {
  508. dispatcher_->addMessageToQueue(std::move(i));
  509. }
  510. }
  511. if (perSecTimer_.difference(global::wallclock()) >= 1_s) {
  512. perSecTimer_ = global::wallclock();
  513. // Drop timeout request after queuing message to give a chance
  514. // to other connection to request piece.
  515. auto indexes = utMetadataRequestTracker_->removeTimeoutEntry();
  516. for (auto idx : indexes) {
  517. pieceStorage_->cancelPiece(pieceStorage_->getPiece(idx), cuid_);
  518. }
  519. }
  520. if (pieceStorage_->downloadFinished()) {
  521. downloadContext_->getOwnerRequestGroup()->setForceHaltRequested(
  522. true, RequestGroup::NONE);
  523. }
  524. }
  525. }
  526. else {
  527. checkActiveInteraction();
  528. if (perSecTimer_.difference(global::wallclock()) >= 1_s) {
  529. perSecTimer_ = global::wallclock();
  530. dispatcher_->checkRequestSlotAndDoNecessaryThing();
  531. }
  532. numReceivedMessage_ = receiveMessages();
  533. detectMessageFlooding();
  534. decideChoking();
  535. decideInterest();
  536. checkHave();
  537. sendKeepAlive();
  538. btRequestFactory_->removeCompletedPiece();
  539. if (!pieceStorage_->downloadFinished()) {
  540. addRequests();
  541. }
  542. }
  543. if (peer_->getExtensionMessageID(ExtensionMessageRegistry::UT_PEX) &&
  544. utPexEnabled_) {
  545. addPeerExchangeMessage();
  546. }
  547. sendPendingMessage();
  548. }
  549. void DefaultBtInteractive::setLocalNode(DHTNode* node) { localNode_ = node; }
  550. size_t DefaultBtInteractive::countPendingMessage()
  551. {
  552. return dispatcher_->countMessageInQueue();
  553. }
  554. bool DefaultBtInteractive::isSendingMessageInProgress()
  555. {
  556. return dispatcher_->isSendingInProgress();
  557. }
  558. size_t DefaultBtInteractive::countReceivedMessageInIteration() const
  559. {
  560. return numReceivedMessage_;
  561. }
  562. size_t DefaultBtInteractive::countOutstandingRequest()
  563. {
  564. if (metadataGetMode_) {
  565. return utMetadataRequestTracker_->count();
  566. }
  567. else {
  568. return dispatcher_->countOutstandingRequest();
  569. }
  570. }
  571. void DefaultBtInteractive::setBtRuntime(
  572. const std::shared_ptr<BtRuntime>& btRuntime)
  573. {
  574. btRuntime_ = btRuntime;
  575. }
  576. void DefaultBtInteractive::setPieceStorage(
  577. const std::shared_ptr<PieceStorage>& pieceStorage)
  578. {
  579. pieceStorage_ = pieceStorage;
  580. }
  581. void DefaultBtInteractive::setPeerStorage(
  582. const std::shared_ptr<PeerStorage>& peerStorage)
  583. {
  584. peerStorage_ = peerStorage;
  585. }
  586. void DefaultBtInteractive::setPeer(const std::shared_ptr<Peer>& peer)
  587. {
  588. peer_ = peer;
  589. }
  590. void DefaultBtInteractive::setBtMessageReceiver(
  591. std::unique_ptr<BtMessageReceiver> receiver)
  592. {
  593. btMessageReceiver_ = std::move(receiver);
  594. }
  595. void DefaultBtInteractive::setDispatcher(
  596. std::unique_ptr<BtMessageDispatcher> dispatcher)
  597. {
  598. dispatcher_ = std::move(dispatcher);
  599. }
  600. void DefaultBtInteractive::setBtRequestFactory(
  601. std::unique_ptr<BtRequestFactory> factory)
  602. {
  603. btRequestFactory_ = std::move(factory);
  604. }
  605. void DefaultBtInteractive::setPeerConnection(
  606. std::unique_ptr<PeerConnection> peerConnection)
  607. {
  608. peerConnection_ = std::move(peerConnection);
  609. }
  610. void DefaultBtInteractive::setExtensionMessageFactory(
  611. std::unique_ptr<ExtensionMessageFactory> factory)
  612. {
  613. extensionMessageFactory_ = std::move(factory);
  614. }
  615. void DefaultBtInteractive::setBtMessageFactory(
  616. std::unique_ptr<BtMessageFactory> factory)
  617. {
  618. messageFactory_ = std::move(factory);
  619. }
  620. void DefaultBtInteractive::setRequestGroupMan(RequestGroupMan* rgman)
  621. {
  622. requestGroupMan_ = rgman;
  623. }
  624. void DefaultBtInteractive::setExtensionMessageRegistry(
  625. std::unique_ptr<ExtensionMessageRegistry> registry)
  626. {
  627. extensionMessageRegistry_ = std::move(registry);
  628. }
  629. void DefaultBtInteractive::setUTMetadataRequestTracker(
  630. std::unique_ptr<UTMetadataRequestTracker> tracker)
  631. {
  632. utMetadataRequestTracker_ = std::move(tracker);
  633. }
  634. void DefaultBtInteractive::setUTMetadataRequestFactory(
  635. std::unique_ptr<UTMetadataRequestFactory> factory)
  636. {
  637. utMetadataRequestFactory_ = std::move(factory);
  638. }
  639. } // namespace aria2