BtPieceMessage.cc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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 <cstring>
  37. #include <cstdlib>
  38. #include <cassert>
  39. #include "bittorrent_helper.h"
  40. #include "util.h"
  41. #include "message.h"
  42. #include "DlAbortEx.h"
  43. #include "MessageDigestHelper.h"
  44. #include "DiskAdaptor.h"
  45. #include "Logger.h"
  46. #include "Peer.h"
  47. #include "Piece.h"
  48. #include "PieceStorage.h"
  49. #include "BtMessageDispatcher.h"
  50. #include "BtMessageFactory.h"
  51. #include "BtRequestFactory.h"
  52. #include "PeerConnection.h"
  53. #include "StringFormat.h"
  54. #include "DownloadContext.h"
  55. namespace aria2 {
  56. const std::string BtPieceMessage::NAME("piece");
  57. void BtPieceMessage::setBlock(const unsigned char* block, size_t blockLength) {
  58. delete [] this->block;
  59. this->blockLength = blockLength;
  60. this->block = new unsigned char[this->blockLength];
  61. memcpy(this->block, block, this->blockLength);
  62. }
  63. BtPieceMessageHandle BtPieceMessage::create(const unsigned char* data, size_t dataLength) {
  64. bittorrent::assertPayloadLengthGreater(9, dataLength, NAME);
  65. bittorrent::assertID(ID, data, NAME);
  66. BtPieceMessageHandle message(new BtPieceMessage());
  67. message->setIndex(bittorrent::getIntParam(data, 1));
  68. message->setBegin(bittorrent::getIntParam(data, 5));
  69. message->setBlock(data+9, dataLength-9);
  70. return message;
  71. }
  72. void BtPieceMessage::doReceivedAction() {
  73. if(_metadataGetMode) {
  74. return;
  75. }
  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*_downloadContext->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. piece->updateHash(begin, block, blockLength);
  93. dispatcher->removeOutstandingRequest(slot);
  94. if(piece->pieceComplete()) {
  95. if(checkPieceHash(piece)) {
  96. onNewPiece(piece);
  97. } else {
  98. onWrongPiece(piece);
  99. }
  100. }
  101. } else {
  102. logger->debug("CUID#%d - RequestSlot not found, index=%d, begin=%d",
  103. cuid, index, begin);
  104. }
  105. }
  106. size_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. bittorrent::createPeerMessageString(msgHeader, MESSAGE_HEADER_LENGTH,
  118. 9+blockLength, ID);
  119. bittorrent::setIntParam(&msgHeader[5], index);
  120. bittorrent::setIntParam(&msgHeader[9], begin);
  121. }
  122. return msgHeader;
  123. }
  124. size_t BtPieceMessage::getMessageHeaderLength() {
  125. return MESSAGE_HEADER_LENGTH;
  126. }
  127. void BtPieceMessage::send() {
  128. if(invalidate) {
  129. return;
  130. }
  131. if(!sendingInProgress) {
  132. logger->info(MSG_SEND_PEER_MESSAGE,
  133. cuid, peer->ipaddr.c_str(), peer->port,
  134. toString().c_str());
  135. getMessageHeader();
  136. peerConnection->sendMessage(msgHeader, getMessageHeaderLength());
  137. off_t pieceDataOffset =
  138. (off_t)index*_downloadContext->getPieceLength()+begin;
  139. size_t writtenLength = sendPieceData(pieceDataOffset, blockLength);
  140. logger->debug("msglength = %lu bytes",
  141. static_cast<unsigned long>(getMessageHeaderLength()+
  142. blockLength));
  143. peer->updateUploadLength(writtenLength);
  144. } else {
  145. ssize_t writtenLength = peerConnection->sendPendingData();
  146. peer->updateUploadLength(writtenLength);
  147. }
  148. sendingInProgress = !peerConnection->sendBufferIsEmpty();
  149. }
  150. size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const {
  151. assert(length <= 16*1024);
  152. unsigned char buf[16*1024];
  153. if(pieceStorage->getDiskAdaptor()->readData(buf, length, offset) ==
  154. static_cast<ssize_t>(length)) {
  155. return peerConnection->sendMessage(buf, length);
  156. } else {
  157. throw DL_ABORT_EX(EX_DATA_READ);
  158. }
  159. }
  160. std::string BtPieceMessage::toString() const {
  161. return strconcat(NAME, " index=", util::itos(index), ", begin=",
  162. util::itos(begin), ", length=", util::itos(blockLength));
  163. }
  164. bool BtPieceMessage::checkPieceHash(const PieceHandle& piece) {
  165. if(piece->isHashCalculated()) {
  166. logger->debug("Hash is available!! index=%lu",
  167. static_cast<unsigned long>(piece->getIndex()));
  168. return
  169. piece->getHashString()==_downloadContext->getPieceHash(piece->getIndex());
  170. } else {
  171. off_t offset = (off_t)piece->getIndex()*_downloadContext->getPieceLength();
  172. return MessageDigestHelper::staticSHA1Digest(pieceStorage->getDiskAdaptor(), offset, piece->getLength())
  173. == _downloadContext->getPieceHash(piece->getIndex());
  174. }
  175. }
  176. void BtPieceMessage::onNewPiece(const PieceHandle& piece) {
  177. logger->info(MSG_GOT_NEW_PIECE, cuid, piece->getIndex());
  178. pieceStorage->completePiece(piece);
  179. pieceStorage->advertisePiece(cuid, piece->getIndex());
  180. }
  181. void BtPieceMessage::onWrongPiece(const PieceHandle& piece) {
  182. logger->info(MSG_GOT_WRONG_PIECE, cuid, piece->getIndex());
  183. erasePieceOnDisk(piece);
  184. piece->clearAllBlock();
  185. piece->destroyHashContext();
  186. requestFactory->removeTargetPiece(piece);
  187. }
  188. void BtPieceMessage::erasePieceOnDisk(const PieceHandle& piece) {
  189. size_t BUFSIZE = 4096;
  190. unsigned char buf[BUFSIZE];
  191. memset(buf, 0, BUFSIZE);
  192. off_t offset = (off_t)piece->getIndex()*_downloadContext->getPieceLength();
  193. div_t res = div(piece->getLength(), BUFSIZE);
  194. for(int i = 0; i < res.quot; ++i) {
  195. pieceStorage->getDiskAdaptor()->writeData(buf, BUFSIZE, offset);
  196. offset += BUFSIZE;
  197. }
  198. if(res.rem > 0) {
  199. pieceStorage->getDiskAdaptor()->writeData(buf, res.rem, offset);
  200. }
  201. }
  202. void BtPieceMessage::onChokingEvent(const BtChokingEvent& event)
  203. {
  204. if(!invalidate &&
  205. !sendingInProgress &&
  206. !peer->isInAmAllowedIndexSet(index)) {
  207. logger->debug(MSG_REJECT_PIECE_CHOKED,
  208. cuid,
  209. index,
  210. begin,
  211. blockLength);
  212. if(peer->isFastExtensionEnabled()) {
  213. BtMessageHandle rej = messageFactory->createRejectMessage(index,
  214. begin,
  215. blockLength);
  216. dispatcher->addMessageToQueue(rej);
  217. }
  218. invalidate = true;
  219. }
  220. }
  221. void BtPieceMessage::onCancelSendingPieceEvent
  222. (const BtCancelSendingPieceEvent& event)
  223. {
  224. if(!invalidate &&
  225. !sendingInProgress &&
  226. index == event.getIndex() &&
  227. begin == event.getBegin() &&
  228. blockLength == event.getLength()) {
  229. logger->debug(MSG_REJECT_PIECE_CANCEL,
  230. cuid, index, begin, blockLength);
  231. if(peer->isFastExtensionEnabled()) {
  232. BtMessageHandle rej = messageFactory->createRejectMessage(index,
  233. begin,
  234. blockLength);
  235. dispatcher->addMessageToQueue(rej);
  236. }
  237. invalidate = true;
  238. }
  239. }
  240. void BtPieceMessage::setDownloadContext
  241. (const SharedHandle<DownloadContext>& downloadContext)
  242. {
  243. _downloadContext = downloadContext;
  244. }
  245. } // namespace aria2