BtPieceMessage.cc 9.3 KB

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