DefaultBtInteractive.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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 "prefs.h"
  37. #include "message.h"
  38. #include "BtHandshakeMessage.h"
  39. #include "Util.h"
  40. #include "BtKeepAliveMessage.h"
  41. #include "BtChokeMessage.h"
  42. #include "BtUnchokeMessage.h"
  43. #include "BtRequestMessage.h"
  44. #include "BtPieceMessage.h"
  45. #include "DlAbortEx.h"
  46. #include "BtExtendedMessage.h"
  47. #include "HandshakeExtensionMessage.h"
  48. #include "UTPexExtensionMessage.h"
  49. #include "DefaultExtensionMessageFactory.h"
  50. #include "BtRegistry.h"
  51. #include "DHTNode.h"
  52. #include "PeerObject.h"
  53. #include "Peer.h"
  54. #include "Piece.h"
  55. #include "BtContext.h"
  56. #include "PieceStorage.h"
  57. #include "PeerStorage.h"
  58. #include "BtRuntime.h"
  59. #include "BtMessageReceiver.h"
  60. #include "BtMessageDispatcher.h"
  61. #include "BtMessageFactory.h"
  62. #include "BtRequestFactory.h"
  63. #include "PeerConnection.h"
  64. #include "BtRegistry.h"
  65. #include "Logger.h"
  66. #include "LogFactory.h"
  67. #include "StringFormat.h"
  68. namespace aria2 {
  69. DefaultBtInteractive::DefaultBtInteractive(const SharedHandle<BtContext>& btContext, const SharedHandle<Peer>& peer):
  70. BtContextAwareCommand(btContext),
  71. peer(peer),
  72. logger(LogFactory::getInstance()),
  73. allowedFastSetSize(10),
  74. keepAliveInterval(120),
  75. maxDownloadSpeedLimit(0),
  76. _utPexEnabled(false),
  77. _dhtEnabled(false),
  78. _numReceivedMessage(0)
  79. {}
  80. DefaultBtInteractive::~DefaultBtInteractive() {}
  81. void DefaultBtInteractive::initiateHandshake() {
  82. SharedHandle<BtMessage> message =
  83. messageFactory->createHandshakeMessage(btContext->getInfoHash(),
  84. btContext->getPeerId());
  85. dispatcher->addMessageToQueue(message);
  86. dispatcher->sendMessages();
  87. }
  88. BtMessageHandle DefaultBtInteractive::receiveHandshake(bool quickReply) {
  89. SharedHandle<BtHandshakeMessage> message =
  90. btMessageReceiver->receiveHandshake(quickReply);
  91. if(message.isNull()) {
  92. return SharedHandle<BtMessage>();
  93. }
  94. peer->setPeerId(message->getPeerId());
  95. if(message->isFastExtensionSupported()) {
  96. peer->setFastExtensionEnabled(true);
  97. logger->info(MSG_FAST_EXTENSION_ENABLED, cuid);
  98. }
  99. if(message->isExtendedMessagingEnabled()) {
  100. peer->setExtendedMessagingEnabled(true);
  101. DefaultExtensionMessageFactoryHandle factory
  102. (new DefaultExtensionMessageFactory(btContext, peer));
  103. if(!_utPexEnabled) {
  104. factory->removeExtension("ut_pex");
  105. }
  106. PEER_OBJECT(btContext, peer)->extensionMessageFactory = factory;
  107. logger->info(MSG_EXTENDED_MESSAGING_ENABLED, cuid);
  108. }
  109. if(message->isDHTEnabled()) {
  110. peer->setDHTEnabled(true);
  111. logger->info(MSG_DHT_ENABLED_PEER, cuid);
  112. }
  113. logger->info(MSG_RECEIVE_PEER_MESSAGE, cuid,
  114. peer->ipaddr.c_str(), peer->port,
  115. message->toString().c_str());
  116. return message;
  117. }
  118. BtMessageHandle DefaultBtInteractive::receiveAndSendHandshake() {
  119. return receiveHandshake(true);
  120. }
  121. void DefaultBtInteractive::doPostHandshakeProcessing() {
  122. // Set time 0 to haveCheckPoint to cache http/ftp download piece completion
  123. haveCheckPoint.setTimeInSec(0);
  124. keepAliveCheckPoint.reset();
  125. floodingCheckPoint.reset();
  126. _pexCheckPoint.setTimeInSec(0);
  127. if(peer->isExtendedMessagingEnabled()) {
  128. addHandshakeExtendedMessageToQueue();
  129. }
  130. addBitfieldMessageToQueue();
  131. if(peer->isDHTEnabled() && _dhtEnabled) {
  132. addPortMessageToQueue();
  133. }
  134. addAllowedFastMessageToQueue();
  135. sendPendingMessage();
  136. }
  137. void DefaultBtInteractive::addPortMessageToQueue()
  138. {
  139. dispatcher->addMessageToQueue(messageFactory->createPortMessage(_localNode->getPort()));
  140. }
  141. void DefaultBtInteractive::addHandshakeExtendedMessageToQueue()
  142. {
  143. HandshakeExtensionMessageHandle m(new HandshakeExtensionMessage());
  144. m->setClientVersion("aria2");
  145. m->setTCPPort(btRuntime->getListenPort());
  146. m->setExtensions(EXTENSION_MESSAGE_FACTORY(btContext, peer)->getExtensions());
  147. SharedHandle<BtMessage> msg = messageFactory->createBtExtendedMessage(m);
  148. dispatcher->addMessageToQueue(msg);
  149. }
  150. void DefaultBtInteractive::addBitfieldMessageToQueue() {
  151. if(peer->isFastExtensionEnabled()) {
  152. if(pieceStorage->allDownloadFinished()) {
  153. dispatcher->addMessageToQueue(messageFactory->createHaveAllMessage());
  154. } else if(pieceStorage->getCompletedLength() > 0) {
  155. dispatcher->addMessageToQueue(messageFactory->createBitfieldMessage());
  156. } else {
  157. dispatcher->addMessageToQueue(messageFactory->createHaveNoneMessage());
  158. }
  159. } else {
  160. if(pieceStorage->getCompletedLength() > 0) {
  161. dispatcher->addMessageToQueue(messageFactory->createBitfieldMessage());
  162. }
  163. }
  164. }
  165. void DefaultBtInteractive::addAllowedFastMessageToQueue() {
  166. if(peer->isFastExtensionEnabled()) {
  167. std::deque<size_t> fastSet = btContext->computeFastSet(peer->ipaddr,
  168. allowedFastSetSize);
  169. for(std::deque<size_t>::const_iterator itr = fastSet.begin();
  170. itr != fastSet.end(); itr++) {
  171. dispatcher->addMessageToQueue(messageFactory->createAllowedFastMessage(*itr));
  172. }
  173. }
  174. }
  175. void DefaultBtInteractive::decideChoking() {
  176. if(peer->shouldBeChoking()) {
  177. if(!peer->amChoking()) {
  178. dispatcher->addMessageToQueue(messageFactory->createChokeMessage());
  179. }
  180. } else {
  181. if(peer->amChoking()) {
  182. dispatcher->addMessageToQueue(messageFactory->createUnchokeMessage());
  183. }
  184. }
  185. }
  186. void DefaultBtInteractive::checkHave() {
  187. std::deque<size_t> indexes =
  188. pieceStorage->getAdvertisedPieceIndexes(cuid, haveCheckPoint);
  189. haveCheckPoint.reset();
  190. if(indexes.size() >= 20) {
  191. if(peer->isFastExtensionEnabled() && pieceStorage->allDownloadFinished()) {
  192. dispatcher->addMessageToQueue(messageFactory->createHaveAllMessage());
  193. } else {
  194. dispatcher->addMessageToQueue(messageFactory->createBitfieldMessage());
  195. }
  196. } else {
  197. for(std::deque<size_t>::iterator itr = indexes.begin(); itr != indexes.end(); itr++) {
  198. dispatcher->addMessageToQueue(messageFactory->createHaveMessage(*itr));
  199. }
  200. }
  201. }
  202. void DefaultBtInteractive::sendKeepAlive() {
  203. if(keepAliveCheckPoint.elapsed(keepAliveInterval)) {
  204. dispatcher->addMessageToQueue(messageFactory->createKeepAliveMessage());
  205. dispatcher->sendMessages();
  206. keepAliveCheckPoint.reset();
  207. }
  208. }
  209. size_t DefaultBtInteractive::receiveMessages() {
  210. size_t msgcount = 0;
  211. for(int i = 0; i < 50; i++) {
  212. if(maxDownloadSpeedLimit > 0) {
  213. TransferStat stat = peerStorage->calculateStat();
  214. if(maxDownloadSpeedLimit < stat.downloadSpeed) {
  215. break;
  216. }
  217. }
  218. BtMessageHandle message = btMessageReceiver->receiveMessage();
  219. if(message.isNull()) {
  220. break;
  221. }
  222. ++msgcount;
  223. logger->info(MSG_RECEIVE_PEER_MESSAGE, cuid,
  224. peer->ipaddr.c_str(), peer->port,
  225. message->toString().c_str());
  226. message->doReceivedAction();
  227. switch(message->getId()) {
  228. case BtKeepAliveMessage::ID:
  229. floodingStat.incKeepAliveCount();
  230. break;
  231. case BtChokeMessage::ID:
  232. if(!peer->peerChoking()) {
  233. floodingStat.incChokeUnchokeCount();
  234. }
  235. break;
  236. case BtUnchokeMessage::ID:
  237. if(peer->peerChoking()) {
  238. floodingStat.incChokeUnchokeCount();
  239. }
  240. break;
  241. case BtRequestMessage::ID:
  242. case BtPieceMessage::ID:
  243. inactiveCheckPoint.reset();
  244. break;
  245. }
  246. }
  247. return msgcount;
  248. }
  249. void DefaultBtInteractive::decideInterest() {
  250. if(pieceStorage->hasMissingPiece(peer)) {
  251. if(!peer->amInterested()) {
  252. logger->debug(MSG_PEER_INTERESTED, cuid);
  253. dispatcher->
  254. addMessageToQueue(messageFactory->createInterestedMessage());
  255. }
  256. } else {
  257. if(peer->amInterested()) {
  258. logger->debug(MSG_PEER_NOT_INTERESTED, cuid);
  259. dispatcher->
  260. addMessageToQueue(messageFactory->createNotInterestedMessage());
  261. }
  262. }
  263. }
  264. void DefaultBtInteractive::fillPiece(size_t maxPieceNum) {
  265. if(pieceStorage->hasMissingPiece(peer)) {
  266. if(peer->peerChoking()) {
  267. if(peer->isFastExtensionEnabled()) {
  268. while(btRequestFactory->countTargetPiece() < maxPieceNum) {
  269. PieceHandle piece = pieceStorage->getMissingFastPiece(peer);
  270. if(piece.isNull()) {
  271. break;
  272. } else {
  273. btRequestFactory->addTargetPiece(piece);
  274. }
  275. }
  276. }
  277. } else {
  278. while(btRequestFactory->countTargetPiece() < maxPieceNum) {
  279. PieceHandle piece = pieceStorage->getMissingPiece(peer);
  280. if(piece.isNull()) {
  281. break;
  282. } else {
  283. btRequestFactory->addTargetPiece(piece);
  284. }
  285. }
  286. }
  287. }
  288. }
  289. void DefaultBtInteractive::addRequests() {
  290. size_t MAX_PENDING_REQUEST;
  291. if(peer->getLatency() < 500) {
  292. MAX_PENDING_REQUEST = 24;
  293. } else if(peer->getLatency() < 1500) {
  294. MAX_PENDING_REQUEST = 12;
  295. } else {
  296. MAX_PENDING_REQUEST = 6;
  297. }
  298. size_t pieceNum;
  299. if(pieceStorage->isEndGame()) {
  300. pieceNum = 1;
  301. } else {
  302. size_t blocks = DIV_FLOOR(btContext->getPieceLength(), Piece::BLOCK_LENGTH);
  303. pieceNum = DIV_FLOOR(MAX_PENDING_REQUEST, blocks);
  304. }
  305. fillPiece(pieceNum);
  306. size_t reqNumToCreate =
  307. MAX_PENDING_REQUEST <= dispatcher->countOutstandingRequest() ?
  308. 0 : MAX_PENDING_REQUEST-dispatcher->countOutstandingRequest();
  309. if(reqNumToCreate > 0) {
  310. BtMessages requests;
  311. if(pieceStorage->isEndGame()) {
  312. requests = btRequestFactory->createRequestMessagesOnEndGame(reqNumToCreate);
  313. } else {
  314. requests = btRequestFactory->createRequestMessages(reqNumToCreate);
  315. }
  316. dispatcher->addMessageToQueue(requests);
  317. }
  318. }
  319. void DefaultBtInteractive::cancelAllPiece() {
  320. btRequestFactory->removeAllTargetPiece();
  321. }
  322. void DefaultBtInteractive::sendPendingMessage() {
  323. dispatcher->sendMessages();
  324. }
  325. void DefaultBtInteractive::detectMessageFlooding() {
  326. if(floodingCheckPoint.elapsed(FLOODING_CHECK_INTERVAL)) {
  327. if(floodingStat.getChokeUnchokeCount() >= 2 ||
  328. floodingStat.getKeepAliveCount() >= 2) {
  329. throw DlAbortEx(EX_FLOODING_DETECTED);
  330. } else {
  331. floodingStat.reset();
  332. }
  333. floodingCheckPoint.reset();
  334. }
  335. }
  336. void DefaultBtInteractive::checkActiveInteraction()
  337. {
  338. // To allow aria2 to accept mutially interested peer, disconnect unintersted
  339. // peer.
  340. {
  341. time_t interval = 30;
  342. if(!peer->amInterested() && !peer->peerInterested() &&
  343. inactiveCheckPoint.elapsed(interval)) {
  344. // TODO change the message
  345. throw DlAbortEx
  346. (StringFormat("Disconnect peer because we are not interested each other after %u second(s).", interval).str());
  347. }
  348. }
  349. // Since the peers which are *just* connected and do nothing to improve
  350. // mutual download progress are completely waste of resources, those peers
  351. // are disconnected in a certain time period.
  352. {
  353. time_t interval = 2*60;
  354. if(inactiveCheckPoint.elapsed(interval)) {
  355. throw DlAbortEx
  356. (StringFormat(EX_DROP_INACTIVE_CONNECTION, interval).str());
  357. }
  358. }
  359. }
  360. void DefaultBtInteractive::addPeerExchangeMessage()
  361. {
  362. time_t interval = 60;
  363. if(_pexCheckPoint.elapsed(interval)) {
  364. UTPexExtensionMessageHandle m
  365. (new UTPexExtensionMessage(peer->getExtensionMessageID("ut_pex")));
  366. const Peers& peers = peerStorage->getPeers();
  367. {
  368. size_t max = 30;
  369. for(Peers::const_iterator i = peers.begin();
  370. i != peers.end() && max; ++i) {
  371. const PeerHandle& cpeer = *i;
  372. if(peer->ipaddr != cpeer->ipaddr &&
  373. !cpeer->getFirstContactTime().elapsed(interval)) {
  374. m->addFreshPeer(cpeer);
  375. --max;
  376. }
  377. }
  378. }
  379. {
  380. size_t max = 10;
  381. for(Peers::const_reverse_iterator i = peers.rbegin();
  382. i != peers.rend() && max; ++i) {
  383. const PeerHandle& cpeer = *i;
  384. if(peer->ipaddr != cpeer->ipaddr &&
  385. !cpeer->getBadConditionStartTime().elapsed(interval)) {
  386. m->addDroppedPeer(cpeer);
  387. --max;
  388. }
  389. }
  390. }
  391. BtMessageHandle msg = messageFactory->createBtExtendedMessage(m);
  392. dispatcher->addMessageToQueue(msg);
  393. _pexCheckPoint.reset();
  394. }
  395. }
  396. void DefaultBtInteractive::doInteractionProcessing() {
  397. checkActiveInteraction();
  398. decideChoking();
  399. detectMessageFlooding();
  400. dispatcher->checkRequestSlotAndDoNecessaryThing();
  401. checkHave();
  402. sendKeepAlive();
  403. _numReceivedMessage = receiveMessages();
  404. btRequestFactory->removeCompletedPiece();
  405. decideInterest();
  406. if(!pieceStorage->downloadFinished()) {
  407. addRequests();
  408. }
  409. if(peer->getExtensionMessageID("ut_pex") && _utPexEnabled) {
  410. addPeerExchangeMessage();
  411. }
  412. sendPendingMessage();
  413. }
  414. void DefaultBtInteractive::setLocalNode(const WeakHandle<DHTNode>& node)
  415. {
  416. _localNode = node;
  417. }
  418. size_t DefaultBtInteractive::countPendingMessage()
  419. {
  420. return dispatcher->countMessageInQueue();
  421. }
  422. bool DefaultBtInteractive::isSendingMessageInProgress()
  423. {
  424. return dispatcher->isSendingInProgress();
  425. }
  426. size_t DefaultBtInteractive::countReceivedMessageInIteration() const
  427. {
  428. return _numReceivedMessage;
  429. }
  430. size_t DefaultBtInteractive::countOutstandingRequest()
  431. {
  432. return dispatcher->countOutstandingRequest();
  433. }
  434. void DefaultBtInteractive::setPeer(const SharedHandle<Peer>& peer)
  435. {
  436. this->peer = peer;
  437. }
  438. void DefaultBtInteractive::setBtMessageReceiver(const BtMessageReceiverWeakHandle& receiver)
  439. {
  440. this->btMessageReceiver = receiver;
  441. }
  442. void DefaultBtInteractive::setDispatcher(const BtMessageDispatcherWeakHandle& dispatcher)
  443. {
  444. this->dispatcher = dispatcher;
  445. }
  446. void DefaultBtInteractive::setBtRequestFactory(const BtRequestFactoryWeakHandle& factory)
  447. {
  448. this->btRequestFactory = factory;
  449. }
  450. void DefaultBtInteractive::setPeerConnection(const PeerConnectionWeakHandle& peerConnection)
  451. {
  452. this->peerConnection = peerConnection;
  453. }
  454. void DefaultBtInteractive::setBtMessageFactory(const BtMessageFactoryWeakHandle& factory)
  455. {
  456. this->messageFactory = factory;
  457. }
  458. } // namespace aria2