BtPieceMessage.cc 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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::setRawMessage(unsigned char* data)
  58. {
  59. delete [] _rawData;
  60. _rawData = data;
  61. this->block = data+9;
  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->setBlockLength(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. SharedHandle<Piece> piece = pieceStorage->getPiece(index);
  83. off_t offset = (off_t)index*_downloadContext->getPieceLength()+begin;
  84. if(logger->debug()) {
  85. logger->debug(MSG_PIECE_RECEIVED,
  86. cuid, index, begin, blockLength, offset,
  87. slot.getBlockIndex());
  88. }
  89. pieceStorage->getDiskAdaptor()->writeData(block, blockLength, offset);
  90. piece->completeBlock(slot.getBlockIndex());
  91. if(logger->debug()) {
  92. logger->debug(MSG_PIECE_BITFIELD, cuid,
  93. util::toHex(piece->getBitfield(),
  94. piece->getBitfieldLength()).c_str());
  95. }
  96. piece->updateHash(begin, block, blockLength);
  97. dispatcher->removeOutstandingRequest(slot);
  98. if(piece->pieceComplete()) {
  99. if(checkPieceHash(piece)) {
  100. onNewPiece(piece);
  101. } else {
  102. onWrongPiece(piece);
  103. }
  104. }
  105. } else {
  106. if(logger->debug()) {
  107. logger->debug("CUID#%d - RequestSlot not found, index=%d, begin=%d",
  108. cuid, index, begin);
  109. }
  110. }
  111. }
  112. size_t BtPieceMessage::MESSAGE_HEADER_LENGTH = 13;
  113. unsigned char* BtPieceMessage::createMessageHeader()
  114. {
  115. /**
  116. * len --- 9+blockLength, 4bytes
  117. * id --- 7, 1byte
  118. * index --- index, 4bytes
  119. * begin --- begin, 4bytes
  120. * total: 13bytes
  121. */
  122. unsigned char* msgHeader = new unsigned char[MESSAGE_HEADER_LENGTH];
  123. bittorrent::createPeerMessageString(msgHeader, MESSAGE_HEADER_LENGTH,
  124. 9+blockLength, ID);
  125. bittorrent::setIntParam(&msgHeader[5], index);
  126. bittorrent::setIntParam(&msgHeader[9], begin);
  127. return msgHeader;
  128. }
  129. size_t BtPieceMessage::getMessageHeaderLength() {
  130. return MESSAGE_HEADER_LENGTH;
  131. }
  132. void BtPieceMessage::send() {
  133. if(invalidate) {
  134. return;
  135. }
  136. size_t writtenLength;
  137. if(!sendingInProgress) {
  138. if(logger->info()) {
  139. logger->info(MSG_SEND_PEER_MESSAGE,
  140. cuid, peer->ipaddr.c_str(), peer->port,
  141. toString().c_str());
  142. }
  143. unsigned char* msgHdr = createMessageHeader();
  144. size_t msgHdrLen = getMessageHeaderLength();
  145. if(logger->debug()) {
  146. logger->debug("msglength = %lu bytes",
  147. static_cast<unsigned long>(msgHdrLen+blockLength));
  148. }
  149. peerConnection->pushBytes(msgHdr, msgHdrLen);
  150. peerConnection->sendPendingData();
  151. off_t pieceDataOffset =
  152. (off_t)index*_downloadContext->getPieceLength()+begin;
  153. writtenLength = sendPieceData(pieceDataOffset, blockLength);
  154. } else {
  155. writtenLength = peerConnection->sendPendingData();
  156. }
  157. peer->updateUploadLength(writtenLength);
  158. sendingInProgress = !peerConnection->sendBufferIsEmpty();
  159. }
  160. size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const {
  161. assert(length <= 16*1024);
  162. unsigned char* buf = new unsigned char[length];
  163. ssize_t r;
  164. try {
  165. r = pieceStorage->getDiskAdaptor()->readData(buf, length, offset);
  166. } catch(RecoverableException& e) {
  167. delete [] buf;
  168. throw;
  169. }
  170. if(r == static_cast<ssize_t>(length)) {
  171. peerConnection->pushBytes(buf, length);
  172. return peerConnection->sendPendingData();
  173. } else {
  174. throw DL_ABORT_EX(EX_DATA_READ);
  175. }
  176. }
  177. std::string BtPieceMessage::toString() const {
  178. return strconcat(NAME, " index=", util::itos(index), ", begin=",
  179. util::itos(begin), ", length=", util::itos(blockLength));
  180. }
  181. bool BtPieceMessage::checkPieceHash(const SharedHandle<Piece>& piece) {
  182. if(piece->isHashCalculated()) {
  183. if(logger->debug()) {
  184. logger->debug("Hash is available!! index=%lu",
  185. static_cast<unsigned long>(piece->getIndex()));
  186. }
  187. return
  188. piece->getHashString()==_downloadContext->getPieceHash(piece->getIndex());
  189. } else {
  190. off_t offset = (off_t)piece->getIndex()*_downloadContext->getPieceLength();
  191. return MessageDigestHelper::staticSHA1Digest(pieceStorage->getDiskAdaptor(), offset, piece->getLength())
  192. == _downloadContext->getPieceHash(piece->getIndex());
  193. }
  194. }
  195. void BtPieceMessage::onNewPiece(const SharedHandle<Piece>& piece) {
  196. logger->info(MSG_GOT_NEW_PIECE, cuid, piece->getIndex());
  197. pieceStorage->completePiece(piece);
  198. pieceStorage->advertisePiece(cuid, piece->getIndex());
  199. }
  200. void BtPieceMessage::onWrongPiece(const SharedHandle<Piece>& piece) {
  201. logger->info(MSG_GOT_WRONG_PIECE, cuid, piece->getIndex());
  202. erasePieceOnDisk(piece);
  203. piece->clearAllBlock();
  204. piece->destroyHashContext();
  205. requestFactory->removeTargetPiece(piece);
  206. }
  207. void BtPieceMessage::erasePieceOnDisk(const SharedHandle<Piece>& piece) {
  208. size_t BUFSIZE = 4096;
  209. unsigned char buf[BUFSIZE];
  210. memset(buf, 0, BUFSIZE);
  211. off_t offset = (off_t)piece->getIndex()*_downloadContext->getPieceLength();
  212. div_t res = div(piece->getLength(), BUFSIZE);
  213. for(int i = 0; i < res.quot; ++i) {
  214. pieceStorage->getDiskAdaptor()->writeData(buf, BUFSIZE, offset);
  215. offset += BUFSIZE;
  216. }
  217. if(res.rem > 0) {
  218. pieceStorage->getDiskAdaptor()->writeData(buf, res.rem, offset);
  219. }
  220. }
  221. void BtPieceMessage::onChokingEvent(const BtChokingEvent& event)
  222. {
  223. if(!invalidate &&
  224. !sendingInProgress &&
  225. !peer->isInAmAllowedIndexSet(index)) {
  226. if(logger->debug()) {
  227. logger->debug(MSG_REJECT_PIECE_CHOKED, cuid, index, begin, blockLength);
  228. }
  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. void BtPieceMessage::onCancelSendingPieceEvent
  239. (const BtCancelSendingPieceEvent& event)
  240. {
  241. if(!invalidate &&
  242. !sendingInProgress &&
  243. index == event.getIndex() &&
  244. begin == event.getBegin() &&
  245. blockLength == event.getLength()) {
  246. if(logger->debug()) {
  247. logger->debug(MSG_REJECT_PIECE_CANCEL, cuid, index, begin, blockLength);
  248. }
  249. if(peer->isFastExtensionEnabled()) {
  250. BtMessageHandle rej = messageFactory->createRejectMessage(index,
  251. begin,
  252. blockLength);
  253. dispatcher->addMessageToQueue(rej);
  254. }
  255. invalidate = true;
  256. }
  257. }
  258. void BtPieceMessage::setDownloadContext
  259. (const SharedHandle<DownloadContext>& downloadContext)
  260. {
  261. _downloadContext = downloadContext;
  262. }
  263. } // namespace aria2