BtPieceMessage.cc 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. RequestSlot slot = dispatcher->getOutstandingRequest(index,
  74. begin,
  75. blockLength);
  76. peer->updateDownloadLength(blockLength);
  77. if(!RequestSlot::isNull(slot)) {
  78. peer->snubbing(false);
  79. peer->updateLatency(slot.getLatencyInMillis());
  80. PieceHandle piece = pieceStorage->getPiece(index);
  81. off_t offset = (off_t)index*_downloadContext->getPieceLength()+begin;
  82. logger->debug(MSG_PIECE_RECEIVED,
  83. cuid, index, begin, blockLength, offset, slot.getBlockIndex());
  84. pieceStorage->getDiskAdaptor()->writeData(block, blockLength, offset);
  85. piece->completeBlock(slot.getBlockIndex());
  86. logger->debug(MSG_PIECE_BITFIELD, cuid,
  87. util::toHex(piece->getBitfield(),
  88. piece->getBitfieldLength()).c_str());
  89. piece->updateHash(begin, block, blockLength);
  90. dispatcher->removeOutstandingRequest(slot);
  91. if(piece->pieceComplete()) {
  92. if(checkPieceHash(piece)) {
  93. onNewPiece(piece);
  94. } else {
  95. onWrongPiece(piece);
  96. }
  97. }
  98. } else {
  99. logger->debug("CUID#%d - RequestSlot not found, index=%d, begin=%d",
  100. cuid, index, begin);
  101. }
  102. }
  103. size_t BtPieceMessage::MESSAGE_HEADER_LENGTH = 13;
  104. const unsigned char* BtPieceMessage::getMessageHeader() {
  105. if(!msgHeader) {
  106. /**
  107. * len --- 9+blockLength, 4bytes
  108. * id --- 7, 1byte
  109. * index --- index, 4bytes
  110. * begin --- begin, 4bytes
  111. * total: 13bytes
  112. */
  113. msgHeader = new unsigned char[MESSAGE_HEADER_LENGTH];
  114. bittorrent::createPeerMessageString(msgHeader, MESSAGE_HEADER_LENGTH,
  115. 9+blockLength, ID);
  116. bittorrent::setIntParam(&msgHeader[5], index);
  117. bittorrent::setIntParam(&msgHeader[9], begin);
  118. }
  119. return msgHeader;
  120. }
  121. size_t BtPieceMessage::getMessageHeaderLength() {
  122. return MESSAGE_HEADER_LENGTH;
  123. }
  124. void BtPieceMessage::send() {
  125. if(invalidate) {
  126. return;
  127. }
  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. peerConnection->sendMessage(msgHeader, getMessageHeaderLength());
  134. off_t pieceDataOffset =
  135. (off_t)index*_downloadContext->getPieceLength()+begin;
  136. size_t writtenLength = sendPieceData(pieceDataOffset, blockLength);
  137. logger->debug("msglength = %lu bytes",
  138. static_cast<unsigned long>(getMessageHeaderLength()+
  139. blockLength));
  140. peer->updateUploadLength(writtenLength);
  141. } else {
  142. ssize_t writtenLength = peerConnection->sendPendingData();
  143. peer->updateUploadLength(writtenLength);
  144. }
  145. sendingInProgress = !peerConnection->sendBufferIsEmpty();
  146. }
  147. size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const {
  148. assert(length <= 16*1024);
  149. unsigned char buf[16*1024];
  150. if(pieceStorage->getDiskAdaptor()->readData(buf, length, offset) ==
  151. static_cast<ssize_t>(length)) {
  152. return peerConnection->sendMessage(buf, length);
  153. } else {
  154. throw DL_ABORT_EX(EX_DATA_READ);
  155. }
  156. }
  157. std::string BtPieceMessage::toString() const {
  158. return strconcat(NAME, " index=", util::itos(index), ", begin=",
  159. util::itos(begin), ", length=", util::itos(blockLength));
  160. }
  161. bool BtPieceMessage::checkPieceHash(const PieceHandle& piece) {
  162. if(piece->isHashCalculated()) {
  163. logger->debug("Hash is available!! index=%lu",
  164. static_cast<unsigned long>(piece->getIndex()));
  165. return
  166. piece->getHashString()==_downloadContext->getPieceHash(piece->getIndex());
  167. } else {
  168. off_t offset = (off_t)piece->getIndex()*_downloadContext->getPieceLength();
  169. return MessageDigestHelper::staticSHA1Digest(pieceStorage->getDiskAdaptor(), offset, piece->getLength())
  170. == _downloadContext->getPieceHash(piece->getIndex());
  171. }
  172. }
  173. void BtPieceMessage::onNewPiece(const PieceHandle& piece) {
  174. logger->info(MSG_GOT_NEW_PIECE, cuid, piece->getIndex());
  175. pieceStorage->completePiece(piece);
  176. pieceStorage->advertisePiece(cuid, piece->getIndex());
  177. }
  178. void BtPieceMessage::onWrongPiece(const PieceHandle& piece) {
  179. logger->info(MSG_GOT_WRONG_PIECE, cuid, piece->getIndex());
  180. erasePieceOnDisk(piece);
  181. piece->clearAllBlock();
  182. piece->destroyHashContext();
  183. requestFactory->removeTargetPiece(piece);
  184. }
  185. void BtPieceMessage::erasePieceOnDisk(const PieceHandle& piece) {
  186. size_t BUFSIZE = 4096;
  187. unsigned char buf[BUFSIZE];
  188. memset(buf, 0, BUFSIZE);
  189. off_t offset = (off_t)piece->getIndex()*_downloadContext->getPieceLength();
  190. div_t res = div(piece->getLength(), BUFSIZE);
  191. for(int i = 0; i < res.quot; ++i) {
  192. pieceStorage->getDiskAdaptor()->writeData(buf, BUFSIZE, offset);
  193. offset += BUFSIZE;
  194. }
  195. if(res.rem > 0) {
  196. pieceStorage->getDiskAdaptor()->writeData(buf, res.rem, offset);
  197. }
  198. }
  199. void BtPieceMessage::onChokingEvent(const BtChokingEvent& event)
  200. {
  201. if(!invalidate &&
  202. !sendingInProgress &&
  203. !peer->isInAmAllowedIndexSet(index)) {
  204. logger->debug(MSG_REJECT_PIECE_CHOKED,
  205. cuid,
  206. index,
  207. begin,
  208. blockLength);
  209. if(peer->isFastExtensionEnabled()) {
  210. BtMessageHandle rej = messageFactory->createRejectMessage(index,
  211. begin,
  212. blockLength);
  213. dispatcher->addMessageToQueue(rej);
  214. }
  215. invalidate = true;
  216. }
  217. }
  218. void BtPieceMessage::onCancelSendingPieceEvent
  219. (const BtCancelSendingPieceEvent& event)
  220. {
  221. if(!invalidate &&
  222. !sendingInProgress &&
  223. index == event.getIndex() &&
  224. begin == event.getBegin() &&
  225. blockLength == event.getLength()) {
  226. logger->debug(MSG_REJECT_PIECE_CANCEL,
  227. cuid, index, begin, blockLength);
  228. if(peer->isFastExtensionEnabled()) {
  229. BtMessageHandle rej = messageFactory->createRejectMessage(index,
  230. begin,
  231. blockLength);
  232. dispatcher->addMessageToQueue(rej);
  233. }
  234. invalidate = true;
  235. }
  236. }
  237. void BtPieceMessage::setDownloadContext
  238. (const SharedHandle<DownloadContext>& downloadContext)
  239. {
  240. _downloadContext = downloadContext;
  241. }
  242. } // namespace aria2