BtPieceMessage.cc 9.5 KB

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