DefaultBtInteractive.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. void DefaultBtInteractive::initiateHandshake() {
  52. BtHandshakeMessageHandle message =
  53. messageFactory->createHandshakeMessage(btContext->getInfoHash(),
  54. btContext->getPeerId());
  55. dispatcher->addMessageToQueue(message);
  56. dispatcher->sendMessages();
  57. }
  58. BtMessageHandle DefaultBtInteractive::receiveHandshake(bool quickReply) {
  59. BtHandshakeMessageHandle message =
  60. btMessageReceiver->receiveHandshake(quickReply);
  61. if(message.isNull()) {
  62. return 0;
  63. }
  64. peer->setPeerId(message->getPeerId());
  65. if(message->isFastExtensionSupported()) {
  66. peer->setFastExtensionEnabled(true);
  67. logger->info(MSG_FAST_EXTENSION_ENABLED, cuid);
  68. }
  69. if(message->isExtendedMessagingEnabled()) {
  70. peer->setExtendedMessagingEnabled(true);
  71. DefaultExtensionMessageFactoryHandle factory =
  72. new DefaultExtensionMessageFactory(btContext, peer);
  73. if(!_utPexEnabled) {
  74. factory->removeExtension("ut_pex");
  75. }
  76. PEER_OBJECT(btContext, peer)->extensionMessageFactory = factory;
  77. logger->info(MSG_EXTENDED_MESSAGING_ENABLED, cuid);
  78. }
  79. logger->info(MSG_RECEIVE_PEER_MESSAGE, cuid,
  80. peer->ipaddr.c_str(), peer->port,
  81. message->toString().c_str());
  82. return message;
  83. }
  84. BtMessageHandle DefaultBtInteractive::receiveAndSendHandshake() {
  85. return receiveHandshake(true);
  86. }
  87. void DefaultBtInteractive::doPostHandshakeProcessing() {
  88. // TODO where is the valid place to rest haveCheckTime?
  89. haveCheckPoint.reset();
  90. keepAliveCheckPoint.reset();
  91. floodingCheckPoint.reset();
  92. _pexCheckPoint.setTimeInSec(0);
  93. if(peer->isExtendedMessagingEnabled()) {
  94. addHandshakeExtendedMessageToQueue();
  95. }
  96. addBitfieldMessageToQueue();
  97. addAllowedFastMessageToQueue();
  98. sendPendingMessage();
  99. }
  100. void DefaultBtInteractive::addHandshakeExtendedMessageToQueue()
  101. {
  102. HandshakeExtensionMessageHandle m = new HandshakeExtensionMessage();
  103. m->setClientVersion("aria2");
  104. m->setTCPPort(btRuntime->getListenPort());
  105. m->setExtensions(EXTENSION_MESSAGE_FACTORY(btContext, peer)->getExtensions());
  106. BtExtendedMessageHandle msg = messageFactory->createBtExtendedMessage(m);
  107. dispatcher->addMessageToQueue(msg);
  108. }
  109. void DefaultBtInteractive::addBitfieldMessageToQueue() {
  110. if(peer->isFastExtensionEnabled()) {
  111. if(pieceStorage->allDownloadFinished()) {
  112. dispatcher->addMessageToQueue(messageFactory->createHaveAllMessage());
  113. } else if(pieceStorage->getCompletedLength() > 0) {
  114. dispatcher->addMessageToQueue(messageFactory->createBitfieldMessage());
  115. } else {
  116. dispatcher->addMessageToQueue(messageFactory->createHaveNoneMessage());
  117. }
  118. } else {
  119. if(pieceStorage->getCompletedLength() > 0) {
  120. dispatcher->addMessageToQueue(messageFactory->createBitfieldMessage());
  121. }
  122. }
  123. }
  124. void DefaultBtInteractive::addAllowedFastMessageToQueue() {
  125. if(peer->isFastExtensionEnabled()) {
  126. Integers fastSet = btContext->computeFastSet(peer->ipaddr,
  127. allowedFastSetSize);
  128. for(Integers::const_iterator itr = fastSet.begin();
  129. itr != fastSet.end(); itr++) {
  130. dispatcher->addMessageToQueue(messageFactory->createAllowedFastMessage(*itr));
  131. }
  132. }
  133. }
  134. void DefaultBtInteractive::decideChoking() {
  135. if(peer->shouldBeChoking()) {
  136. if(!peer->amChoking) {
  137. dispatcher->addMessageToQueue(messageFactory->createChokeMessage());
  138. }
  139. } else {
  140. if(peer->amChoking) {
  141. dispatcher->addMessageToQueue(messageFactory->createUnchokeMessage());
  142. }
  143. }
  144. }
  145. void DefaultBtInteractive::checkHave() {
  146. Integers indexes =
  147. pieceStorage->getAdvertisedPieceIndexes(cuid, haveCheckPoint);
  148. haveCheckPoint.reset();
  149. if(indexes.size() >= 20) {
  150. if(peer->isFastExtensionEnabled() && pieceStorage->allDownloadFinished()) {
  151. dispatcher->addMessageToQueue(messageFactory->createHaveAllMessage());
  152. } else {
  153. dispatcher->addMessageToQueue(messageFactory->createBitfieldMessage());
  154. }
  155. } else {
  156. for(Integers::iterator itr = indexes.begin(); itr != indexes.end(); itr++) {
  157. dispatcher->addMessageToQueue(messageFactory->createHaveMessage(*itr));
  158. }
  159. }
  160. }
  161. void DefaultBtInteractive::sendKeepAlive() {
  162. if(keepAliveCheckPoint.elapsed(keepAliveInterval)) {
  163. dispatcher->addMessageToQueue(messageFactory->createKeepAliveMessage());
  164. dispatcher->sendMessages();
  165. keepAliveCheckPoint.reset();
  166. }
  167. }
  168. void DefaultBtInteractive::receiveMessages() {
  169. for(int i = 0; i < 50; i++) {
  170. if(maxDownloadSpeedLimit > 0) {
  171. TransferStat stat = peerStorage->calculateStat();
  172. if(maxDownloadSpeedLimit < stat.downloadSpeed) {
  173. break;
  174. }
  175. }
  176. BtMessageHandle message = btMessageReceiver->receiveMessage();
  177. if(message.isNull()) {
  178. break;
  179. }
  180. logger->info(MSG_RECEIVE_PEER_MESSAGE, cuid,
  181. peer->ipaddr.c_str(), peer->port,
  182. message->toString().c_str());
  183. message->doReceivedAction();
  184. switch(message->getId()) {
  185. case BtKeepAliveMessage::ID:
  186. floodingStat.incKeepAliveCount();
  187. break;
  188. case BtChokeMessage::ID:
  189. if(!peer->peerChoking) {
  190. floodingStat.incChokeUnchokeCount();
  191. }
  192. break;
  193. case BtUnchokeMessage::ID:
  194. if(peer->peerChoking) {
  195. floodingStat.incChokeUnchokeCount();
  196. }
  197. break;
  198. case BtRequestMessage::ID:
  199. case BtPieceMessage::ID:
  200. inactiveCheckPoint.reset();
  201. break;
  202. }
  203. }
  204. }
  205. void DefaultBtInteractive::decideInterest() {
  206. if(pieceStorage->hasMissingPiece(peer)) {
  207. if(!peer->amInterested) {
  208. logger->debug(MSG_PEER_INTERESTED, cuid);
  209. dispatcher->
  210. addMessageToQueue(messageFactory->createInterestedMessage());
  211. }
  212. } else {
  213. if(peer->amInterested) {
  214. logger->debug(MSG_PEER_NOT_INTERESTED, cuid);
  215. dispatcher->
  216. addMessageToQueue(messageFactory->createNotInterestedMessage());
  217. }
  218. }
  219. }
  220. void DefaultBtInteractive::fillPiece(int maxPieceNum) {
  221. if(pieceStorage->hasMissingPiece(peer)) {
  222. if(peer->peerChoking) {
  223. if(peer->isFastExtensionEnabled()) {
  224. while(btRequestFactory->countTargetPiece() < maxPieceNum) {
  225. PieceHandle piece = pieceStorage->getMissingFastPiece(peer);
  226. if(piece.isNull()) {
  227. break;
  228. } else {
  229. btRequestFactory->addTargetPiece(piece);
  230. }
  231. }
  232. }
  233. } else {
  234. while(btRequestFactory->countTargetPiece() < maxPieceNum) {
  235. PieceHandle piece = pieceStorage->getMissingPiece(peer);
  236. if(piece.isNull()) {
  237. break;
  238. } else {
  239. btRequestFactory->addTargetPiece(piece);
  240. }
  241. }
  242. }
  243. }
  244. }
  245. void DefaultBtInteractive::addRequests() {
  246. int32_t MAX_PENDING_REQUEST;
  247. if(peer->getLatency() < 500) {
  248. MAX_PENDING_REQUEST = 24;
  249. } else if(peer->getLatency() < 1500) {
  250. MAX_PENDING_REQUEST = 12;
  251. } else {
  252. MAX_PENDING_REQUEST = 6;
  253. }
  254. int32_t pieceNum;
  255. if(pieceStorage->isEndGame()) {
  256. pieceNum = 1;
  257. } else {
  258. int32_t blocks = DIV_FLOOR(btContext->getPieceLength(), Piece::BLOCK_LENGTH);
  259. pieceNum = DIV_FLOOR(MAX_PENDING_REQUEST, blocks);
  260. }
  261. fillPiece(pieceNum);
  262. int32_t reqNumToCreate =
  263. MAX_PENDING_REQUEST <= dispatcher->countOutstandingRequest() ?
  264. 0 : MAX_PENDING_REQUEST-dispatcher->countOutstandingRequest();
  265. if(reqNumToCreate > 0) {
  266. BtMessages requests;
  267. if(pieceStorage->isEndGame()) {
  268. requests = btRequestFactory->createRequestMessagesOnEndGame(reqNumToCreate);
  269. } else {
  270. requests = btRequestFactory->createRequestMessages(reqNumToCreate);
  271. }
  272. dispatcher->addMessageToQueue(requests);
  273. }
  274. }
  275. void DefaultBtInteractive::cancelAllPiece() {
  276. btRequestFactory->removeAllTargetPiece();
  277. }
  278. void DefaultBtInteractive::sendPendingMessage() {
  279. dispatcher->sendMessages();
  280. }
  281. void DefaultBtInteractive::detectMessageFlooding() {
  282. if(floodingCheckPoint.elapsed(FLOODING_CHECK_INTERVAL)) {
  283. if(floodingStat.getChokeUnchokeCount() >= 2 ||
  284. floodingStat.getKeepAliveCount() >= 2) {
  285. throw new DlAbortEx(EX_FLOODING_DETECTED);
  286. } else {
  287. floodingStat.reset();
  288. }
  289. floodingCheckPoint.reset();
  290. }
  291. }
  292. void DefaultBtInteractive::checkActiveInteraction()
  293. {
  294. int32_t interval = 5*60;
  295. if(inactiveCheckPoint.elapsed(interval)) {
  296. throw new DlAbortEx(EX_DROP_INACTIVE_CONNECTION, interval);
  297. }
  298. }
  299. void DefaultBtInteractive::addPeerExchangeMessage()
  300. {
  301. time_t interval = 60;
  302. if(_pexCheckPoint.elapsed(interval)) {
  303. UTPexExtensionMessageHandle m =
  304. new UTPexExtensionMessage(peer->getExtensionMessageID("ut_pex"));
  305. const Peers& peers = peerStorage->getPeers();
  306. {
  307. size_t max = 30;
  308. for(Peers::const_iterator i = peers.begin();
  309. i != peers.end() && max; ++i) {
  310. const PeerHandle& cpeer = *i;
  311. if(peer->ipaddr != cpeer->ipaddr &&
  312. !cpeer->getFirstContactTime().elapsed(interval) &&
  313. Util::isNumbersAndDotsNotation(cpeer->ipaddr)) {
  314. m->addFreshPeer(cpeer);
  315. --max;
  316. }
  317. }
  318. }
  319. {
  320. size_t max = 10;
  321. for(Peers::const_reverse_iterator i = peers.rbegin();
  322. i != peers.rend() && max; ++i) {
  323. const PeerHandle& cpeer = *i;
  324. if(peer->ipaddr != cpeer->ipaddr &&
  325. !cpeer->getBadConditionStartTime().elapsed(interval) &&
  326. Util::isNumbersAndDotsNotation(cpeer->ipaddr)) {
  327. m->addDroppedPeer(cpeer);
  328. --max;
  329. }
  330. }
  331. }
  332. BtExtendedMessageHandle msg = messageFactory->createBtExtendedMessage(m);
  333. dispatcher->addMessageToQueue(msg);
  334. _pexCheckPoint.reset();
  335. }
  336. }
  337. void DefaultBtInteractive::doInteractionProcessing() {
  338. checkActiveInteraction();
  339. decideChoking();
  340. detectMessageFlooding();
  341. dispatcher->checkRequestSlotAndDoNecessaryThing();
  342. checkHave();
  343. sendKeepAlive();
  344. receiveMessages();
  345. btRequestFactory->removeCompletedPiece();
  346. decideInterest();
  347. if(!pieceStorage->downloadFinished()) {
  348. addRequests();
  349. }
  350. if(peer->getExtensionMessageID("ut_pex") && _utPexEnabled) {
  351. addPeerExchangeMessage();
  352. }
  353. sendPendingMessage();
  354. }