BtPieceMessage.cc 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 "BtPieceMessage.h"
  36. #include "PeerMessageUtil.h"
  37. #include "Util.h"
  38. #include "message.h"
  39. #include "DlAbortEx.h"
  40. #include "BtChokingEvent.h"
  41. #include "BtCancelSendingPieceEvent.h"
  42. #include "MessageDigestHelper.h"
  43. #include "DiskAdaptor.h"
  44. #include "Logger.h"
  45. #include "Peer.h"
  46. #include "Piece.h"
  47. #include "BtContext.h"
  48. #include "PieceStorage.h"
  49. #include "BtMessageDispatcher.h"
  50. #include "BtMessageFactory.h"
  51. #include "BtRequestFactory.h"
  52. #include "PeerConnection.h"
  53. #include <cstring>
  54. namespace aria2 {
  55. void BtPieceMessage::setBlock(const unsigned char* block, int32_t blockLength) {
  56. delete [] this->block;
  57. this->blockLength = blockLength;
  58. this->block = new unsigned char[this->blockLength];
  59. memcpy(this->block, block, this->blockLength);
  60. }
  61. BtPieceMessageHandle BtPieceMessage::create(const unsigned char* data, int32_t dataLength) {
  62. if(dataLength <= 9) {
  63. throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "piece", dataLength, 9);
  64. }
  65. int8_t id = PeerMessageUtil::getId(data);
  66. if(id != ID) {
  67. throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "piece", ID);
  68. }
  69. BtPieceMessageHandle message = new BtPieceMessage();
  70. message->setIndex(PeerMessageUtil::getIntParam(data, 1));
  71. message->setBegin(PeerMessageUtil::getIntParam(data, 5));
  72. message->setBlock(data+9, dataLength-9);
  73. return message;
  74. }
  75. void BtPieceMessage::doReceivedAction() {
  76. RequestSlot slot = dispatcher->getOutstandingRequest(index,
  77. begin,
  78. blockLength);
  79. peer->updateDownloadLength(blockLength);
  80. if(!RequestSlot::isNull(slot)) {
  81. peer->snubbing(false);
  82. peer->updateLatency(slot.getLatencyInMillis());
  83. PieceHandle piece = pieceStorage->getPiece(index);
  84. int64_t offset =
  85. ((int64_t)index)*btContext->getPieceLength()+begin;
  86. logger->debug(MSG_PIECE_RECEIVED,
  87. cuid, index, begin, blockLength, offset, slot.getBlockIndex());
  88. pieceStorage->getDiskAdaptor()->writeData(block,
  89. blockLength,
  90. offset);
  91. piece->completeBlock(slot.getBlockIndex());
  92. logger->debug(MSG_PIECE_BITFIELD,
  93. cuid,
  94. Util::toHex(piece->getBitfield(),
  95. piece->getBitfieldLength()).c_str());
  96. dispatcher->removeOutstandingRequest(slot);
  97. if(piece->pieceComplete()) {
  98. if(checkPieceHash(piece)) {
  99. onNewPiece(piece);
  100. } else {
  101. onWrongPiece(piece);
  102. }
  103. }
  104. }
  105. }
  106. int32_t BtPieceMessage::MESSAGE_HEADER_LENGTH = 13;
  107. const unsigned char* BtPieceMessage::getMessageHeader() {
  108. if(!msgHeader) {
  109. /**
  110. * len --- 9+blockLength, 4bytes
  111. * id --- 7, 1byte
  112. * index --- index, 4bytes
  113. * begin --- begin, 4bytes
  114. * total: 13bytes
  115. */
  116. msgHeader = new unsigned char[MESSAGE_HEADER_LENGTH];
  117. PeerMessageUtil::createPeerMessageString(msgHeader, MESSAGE_HEADER_LENGTH,
  118. 9+blockLength, ID);
  119. PeerMessageUtil::setIntParam(&msgHeader[5], index);
  120. PeerMessageUtil::setIntParam(&msgHeader[9], begin);
  121. }
  122. return msgHeader;
  123. }
  124. int32_t BtPieceMessage::getMessageHeaderLength() {
  125. return MESSAGE_HEADER_LENGTH;
  126. }
  127. void BtPieceMessage::send() {
  128. if(invalidate) {
  129. return;
  130. }
  131. if(!headerSent) {
  132. if(!sendingInProgress) {
  133. logger->info(MSG_SEND_PEER_MESSAGE,
  134. cuid, peer->ipaddr.c_str(), peer->port,
  135. toString().c_str());
  136. getMessageHeader();
  137. leftDataLength = getMessageHeaderLength();
  138. sendingInProgress = true;
  139. }
  140. int32_t writtenLength
  141. = peerConnection->sendMessage(msgHeader+getMessageHeaderLength()-leftDataLength,
  142. leftDataLength);
  143. if(writtenLength == leftDataLength) {
  144. headerSent = true;
  145. leftDataLength = blockLength;
  146. } else {
  147. leftDataLength -= writtenLength;
  148. }
  149. }
  150. if(headerSent) {
  151. sendingInProgress = false;
  152. int64_t pieceDataOffset =
  153. ((int64_t)index)*btContext->getPieceLength()+begin+blockLength-leftDataLength;
  154. int32_t writtenLength =
  155. sendPieceData(pieceDataOffset, leftDataLength);
  156. peer->updateUploadLength(writtenLength);
  157. if(writtenLength < leftDataLength) {
  158. sendingInProgress = true;
  159. }
  160. leftDataLength -= writtenLength;
  161. }
  162. }
  163. int32_t BtPieceMessage::sendPieceData(int64_t offset, int32_t length) const {
  164. int32_t BUF_SIZE = 256;
  165. unsigned char buf[BUF_SIZE];
  166. int32_t iteration = length/BUF_SIZE;
  167. int32_t writtenLength = 0;
  168. for(int32_t i = 0; i < iteration; i++) {
  169. if(pieceStorage->getDiskAdaptor()->readData(buf, BUF_SIZE, offset+i*BUF_SIZE) < BUF_SIZE) {
  170. throw new DlAbortEx(EX_DATA_READ);
  171. }
  172. int32_t ws = peerConnection->sendMessage(buf, BUF_SIZE);
  173. writtenLength += ws;
  174. if(ws != BUF_SIZE) {
  175. return writtenLength;
  176. }
  177. }
  178. int32_t rem = length%BUF_SIZE;
  179. if(rem > 0) {
  180. if(pieceStorage->getDiskAdaptor()->readData(buf, rem, offset+iteration*BUF_SIZE) < rem) {
  181. throw new DlAbortEx(EX_DATA_READ);
  182. }
  183. int32_t ws = peerConnection->sendMessage(buf, rem);
  184. writtenLength += ws;
  185. }
  186. return writtenLength;
  187. }
  188. std::string BtPieceMessage::toString() const {
  189. return "piece index="+Util::itos(index)+", begin="+Util::itos(begin)+
  190. ", length="+Util::itos(blockLength);
  191. }
  192. bool BtPieceMessage::checkPieceHash(const PieceHandle& piece) {
  193. int64_t offset =
  194. ((int64_t)piece->getIndex())*btContext->getPieceLength();
  195. return MessageDigestHelper::digest("sha1", pieceStorage->getDiskAdaptor(), offset, piece->getLength())
  196. == btContext->getPieceHash(piece->getIndex());
  197. }
  198. void BtPieceMessage::onNewPiece(const PieceHandle& piece) {
  199. logger->info(MSG_GOT_NEW_PIECE, cuid, piece->getIndex());
  200. pieceStorage->completePiece(piece);
  201. pieceStorage->advertisePiece(cuid, piece->getIndex());
  202. }
  203. void BtPieceMessage::onWrongPiece(const PieceHandle& piece) {
  204. logger->info(MSG_GOT_WRONG_PIECE, cuid, piece->getIndex());
  205. erasePieceOnDisk(piece);
  206. piece->clearAllBlock();
  207. requestFactory->removeTargetPiece(piece);
  208. }
  209. void BtPieceMessage::erasePieceOnDisk(const PieceHandle& piece) {
  210. int32_t BUFSIZE = 4096;
  211. unsigned char buf[BUFSIZE];
  212. memset(buf, 0, BUFSIZE);
  213. int64_t offset =
  214. ((int64_t)piece->getIndex())*btContext->getPieceLength();
  215. for(int32_t i = 0; i < piece->getLength()/BUFSIZE; i++) {
  216. pieceStorage->getDiskAdaptor()->writeData(buf, BUFSIZE, offset);
  217. offset += BUFSIZE;
  218. }
  219. int32_t r = piece->getLength()%BUFSIZE;
  220. if(r > 0) {
  221. pieceStorage->getDiskAdaptor()->writeData(buf, r, offset);
  222. }
  223. }
  224. bool BtPieceMessage::BtChokingEventListener::canHandle(const BtEventHandle& event) {
  225. BtChokingEvent* intEvent = dynamic_cast<BtChokingEvent*>(event.get());
  226. return intEvent != 0;
  227. }
  228. void BtPieceMessage::BtChokingEventListener::handleEventInternal(const BtEventHandle& event) {
  229. message->handleChokingEvent(event);
  230. }
  231. void BtPieceMessage::handleChokingEvent(const BtEventHandle& event) {
  232. if(!invalidate &&
  233. !sendingInProgress &&
  234. !peer->isInAmAllowedIndexSet(index)) {
  235. logger->debug(MSG_REJECT_PIECE_CHOKED,
  236. cuid,
  237. index,
  238. begin,
  239. blockLength);
  240. if(peer->isFastExtensionEnabled()) {
  241. BtMessageHandle rej = messageFactory->createRejectMessage(index,
  242. begin,
  243. blockLength);
  244. dispatcher->addMessageToQueue(rej);
  245. }
  246. invalidate = true;
  247. }
  248. }
  249. bool BtPieceMessage::BtCancelSendingPieceEventListener::canHandle(const BtEventHandle& event) {
  250. BtCancelSendingPieceEvent* intEvent = dynamic_cast<BtCancelSendingPieceEvent*>(event.get());
  251. return intEvent != 0;
  252. }
  253. void BtPieceMessage::BtCancelSendingPieceEventListener::handleEventInternal(const BtEventHandle& event) {
  254. message->handleCancelSendingPieceEvent(event);
  255. }
  256. void BtPieceMessage::handleCancelSendingPieceEvent(const BtEventHandle& event) {
  257. BtCancelSendingPieceEvent* intEvent = (BtCancelSendingPieceEvent*)(event.get());
  258. if(!invalidate &&
  259. !sendingInProgress &&
  260. index == intEvent->getIndex() &&
  261. begin == intEvent->getBegin() &&
  262. blockLength == intEvent->getLength()) {
  263. logger->debug(MSG_REJECT_PIECE_CANCEL,
  264. cuid, index, begin, blockLength);
  265. if(peer->isFastExtensionEnabled()) {
  266. BtMessageHandle rej = messageFactory->createRejectMessage(index,
  267. begin,
  268. blockLength);
  269. dispatcher->addMessageToQueue(rej);
  270. }
  271. invalidate = true;
  272. }
  273. }
  274. } // namespace aria2