PeerInteractionCommand.cc 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 "PeerInteractionCommand.h"
  36. #include "PeerInitiateConnectionCommand.h"
  37. #include "PeerMessageUtil.h"
  38. #include "HandshakeMessage.h"
  39. #include "KeepAliveMessage.h"
  40. #include "ChokeMessage.h"
  41. #include "UnchokeMessage.h"
  42. #include "HaveMessage.h"
  43. #include "DlAbortEx.h"
  44. #include "Util.h"
  45. #include "message.h"
  46. #include "prefs.h"
  47. #include <algorithm>
  48. PeerInteractionCommand::PeerInteractionCommand(int cuid,
  49. const PeerHandle& p,
  50. TorrentDownloadEngine* e,
  51. const SocketHandle& s,
  52. int sequence)
  53. :PeerAbstractCommand(cuid, p, e, s), sequence(sequence) {
  54. if(sequence == INITIATOR_SEND_HANDSHAKE) {
  55. disableReadCheckSocket();
  56. setWriteCheckSocket(socket);
  57. setTimeout(e->option->getAsInt(PREF_PEER_CONNECTION_TIMEOUT));
  58. }
  59. peerInteraction = new PeerInteraction(cuid, peer, socket, e->option,
  60. e->torrentMan);
  61. setUploadLimit(e->option->getAsInt(PREF_MAX_UPLOAD_LIMIT));
  62. chokeUnchokeCount = 0;
  63. haveCount = 0;
  64. keepAliveCount = 0;
  65. e->torrentMan->addActivePeer(peer);
  66. }
  67. PeerInteractionCommand::~PeerInteractionCommand() {
  68. delete peerInteraction;
  69. e->torrentMan->deleteActivePeer(peer);
  70. }
  71. bool PeerInteractionCommand::executeInternal() {
  72. disableWriteCheckSocket();
  73. setUploadLimitCheck(false);
  74. setNoCheck(false);
  75. switch(sequence) {
  76. case INITIATOR_SEND_HANDSHAKE:
  77. if(!socket->isWritable(0)) {
  78. setWriteCheckSocket(socket);
  79. break;
  80. }
  81. socket->setBlockingMode();
  82. setReadCheckSocket(socket);
  83. setTimeout(e->option->getAsInt(PREF_TIMEOUT));
  84. peerInteraction->sendHandshake();
  85. sequence = INITIATOR_WAIT_HANDSHAKE;
  86. break;
  87. case INITIATOR_WAIT_HANDSHAKE: {
  88. if(peerInteraction->countMessageInQueue() > 0) {
  89. peerInteraction->sendMessages();
  90. if(peerInteraction->countMessageInQueue() > 0) {
  91. break;
  92. }
  93. }
  94. PeerMessageHandle handshakeMessage =
  95. peerInteraction->receiveHandshake();
  96. if(handshakeMessage.get() == 0) {
  97. break;
  98. }
  99. peer->setPeerId(((HandshakeMessage*)handshakeMessage.get())->peerId);
  100. logger->info(MSG_RECEIVE_PEER_MESSAGE, cuid,
  101. peer->ipaddr.c_str(), peer->port,
  102. handshakeMessage->toString().c_str());
  103. haveCheckTime.reset();
  104. peerInteraction->sendBitfield();
  105. peerInteraction->sendAllowedFast();
  106. sequence = WIRED;
  107. break;
  108. }
  109. case RECEIVER_WAIT_HANDSHAKE: {
  110. PeerMessageHandle handshakeMessage =
  111. peerInteraction->receiveHandshake(true);
  112. if(handshakeMessage.get() == 0) {
  113. break;
  114. }
  115. peer->setPeerId(((HandshakeMessage*)handshakeMessage.get())->peerId);
  116. logger->info(MSG_RECEIVE_PEER_MESSAGE, cuid,
  117. peer->ipaddr.c_str(), peer->port,
  118. handshakeMessage->toString().c_str());
  119. haveCheckTime.reset();
  120. peerInteraction->sendBitfield();
  121. peerInteraction->sendAllowedFast();
  122. sequence = WIRED;
  123. break;
  124. }
  125. case WIRED:
  126. peerInteraction->syncPiece();
  127. decideChoking();
  128. if(periodicExecPoint.elapsedInMillis(500)) {
  129. periodicExecPoint.reset();
  130. detectMessageFlooding();
  131. peerInteraction->checkRequestSlot();
  132. checkHave();
  133. sendKeepAlive();
  134. }
  135. receiveMessages();
  136. peerInteraction->addRequests();
  137. peerInteraction->sendMessages();
  138. break;
  139. }
  140. if(peerInteraction->countMessageInQueue() > 0) {
  141. if(peerInteraction->isSendingMessageInProgress()) {
  142. setUploadLimitCheck(true);
  143. }
  144. setNoCheck(true);
  145. }
  146. e->commands.push_back(this);
  147. return false;
  148. }
  149. #define FLOODING_CHECK_INTERVAL 5
  150. void PeerInteractionCommand::detectMessageFlooding() {
  151. if(freqCheckPoint.elapsed(FLOODING_CHECK_INTERVAL)) {
  152. if(chokeUnchokeCount*1.0/FLOODING_CHECK_INTERVAL >= 0.4
  153. //|| haveCount*1.0/elapsed >= 20.0
  154. || keepAliveCount*1.0/FLOODING_CHECK_INTERVAL >= 1.0) {
  155. throw new DlAbortEx("Flooding detected.");
  156. } else {
  157. chokeUnchokeCount = 0;
  158. haveCount = 0;
  159. keepAliveCount = 0;
  160. freqCheckPoint.reset();
  161. }
  162. }
  163. }
  164. /*
  165. void PeerInteractionCommand::checkLongTimePeerChoking() {
  166. if(e->torrentMan->downloadComplete()) {
  167. return;
  168. }
  169. if(peer->amInterested && peer->peerChoking) {
  170. if(chokeCheckPoint.elapsed(MAX_PEER_CHOKING_INTERVAL)) {
  171. logger->info("CUID#%d - The peer is choking too long.", cuid);
  172. peer->snubbing = true;
  173. }
  174. } else {
  175. chokeCheckPoint.reset();
  176. }
  177. }
  178. */
  179. void PeerInteractionCommand::decideChoking() {
  180. if(peer->shouldBeChoking()) {
  181. if(!peer->amChoking) {
  182. peerInteraction->addMessage(peerInteraction->getPeerMessageFactory()->
  183. createChokeMessage());
  184. }
  185. } else {
  186. if(peer->amChoking) {
  187. peerInteraction->addMessage(peerInteraction->getPeerMessageFactory()->
  188. createUnchokeMessage());
  189. }
  190. }
  191. }
  192. void PeerInteractionCommand::receiveMessages() {
  193. for(int i = 0; i < 50; i++) {
  194. int maxSpeedLimit = e->option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT);
  195. if(maxSpeedLimit > 0) {
  196. TransferStat stat = e->torrentMan->calculateStat();
  197. if(maxSpeedLimit < stat.downloadSpeed) {
  198. disableReadCheckSocket();
  199. setNoCheck(true);
  200. break;
  201. }
  202. }
  203. PeerMessageHandle message = peerInteraction->receiveMessage();
  204. if(message.get() == NULL) {
  205. return;
  206. }
  207. logger->info(MSG_RECEIVE_PEER_MESSAGE, cuid,
  208. peer->ipaddr.c_str(), peer->port,
  209. message->toString().c_str());
  210. // to detect flooding
  211. switch(message->getId()) {
  212. case KeepAliveMessage::ID:
  213. keepAliveCount++;
  214. break;
  215. case ChokeMessage::ID:
  216. if(!peer->peerChoking) {
  217. chokeUnchokeCount++;
  218. }
  219. break;
  220. case UnchokeMessage::ID:
  221. if(peer->peerChoking) {
  222. chokeUnchokeCount++;
  223. }
  224. break;
  225. case HaveMessage::ID:
  226. haveCount++;
  227. break;
  228. }
  229. message->receivedAction();
  230. }
  231. }
  232. // TODO this method removed when PeerBalancerCommand is implemented
  233. bool PeerInteractionCommand::prepareForNextPeer(int wait) {
  234. if(e->torrentMan->isPeerAvailable()) {
  235. PeerHandle peer = e->torrentMan->getPeer();
  236. int newCuid = e->torrentMan->getNewCuid();
  237. peer->cuid = newCuid;
  238. PeerInitiateConnectionCommand* command =
  239. new PeerInitiateConnectionCommand(newCuid, peer, e);
  240. e->commands.push_back(command);
  241. }
  242. return true;
  243. }
  244. bool PeerInteractionCommand::prepareForRetry(int wait) {
  245. e->commands.push_back(this);
  246. return false;
  247. }
  248. void PeerInteractionCommand::onAbort(Exception* ex) {
  249. peerInteraction->abortAllPieces();
  250. PeerAbstractCommand::onAbort(ex);
  251. }
  252. void PeerInteractionCommand::sendKeepAlive() {
  253. if(keepAliveCheckPoint.elapsed(KEEP_ALIVE_INTERVAL)) {
  254. if(peerInteraction->countMessageInQueue() == 0) {
  255. peerInteraction->addMessage(peerInteraction->getPeerMessageFactory()->
  256. createKeepAliveMessage());
  257. peerInteraction->sendMessages();
  258. }
  259. keepAliveCheckPoint.reset();
  260. }
  261. }
  262. void PeerInteractionCommand::checkHave() {
  263. PieceIndexes indexes =
  264. e->torrentMan->getAdvertisedPieceIndexes(cuid, haveCheckTime);
  265. haveCheckTime.reset();
  266. if(indexes.size() >= 20) {
  267. if(peer->isFastExtensionEnabled()) {
  268. if(e->torrentMan->hasAllPieces()) {
  269. peerInteraction->addMessage(peerInteraction->getPeerMessageFactory()->
  270. createHaveAllMessage());
  271. } else {
  272. peerInteraction->addMessage(peerInteraction->getPeerMessageFactory()->
  273. createBitfieldMessage());
  274. }
  275. } else {
  276. peerInteraction->addMessage(peerInteraction->getPeerMessageFactory()->
  277. createBitfieldMessage());
  278. }
  279. } else {
  280. for(PieceIndexes::iterator itr = indexes.begin(); itr != indexes.end(); itr++) {
  281. peerInteraction->addMessage(peerInteraction->getPeerMessageFactory()->
  282. createHaveMessage(*itr));
  283. }
  284. }
  285. }