BtPieceMessage.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 "message_digest_helper.h"
  44. #include "DiskAdaptor.h"
  45. #include "Logger.h"
  46. #include "LogFactory.h"
  47. #include "Peer.h"
  48. #include "Piece.h"
  49. #include "PieceStorage.h"
  50. #include "BtMessageDispatcher.h"
  51. #include "BtMessageFactory.h"
  52. #include "BtRequestFactory.h"
  53. #include "PeerConnection.h"
  54. #include "fmt.h"
  55. #include "DownloadContext.h"
  56. namespace aria2 {
  57. const std::string BtPieceMessage::NAME("piece");
  58. BtPieceMessage::BtPieceMessage
  59. (size_t index, uint32_t begin, size_t blockLength)
  60. : AbstractBtMessage(ID, NAME),
  61. index_(index),
  62. begin_(begin),
  63. blockLength_(blockLength),
  64. block_(0),
  65. rawData_(0)
  66. {
  67. setUploading(true);
  68. }
  69. BtPieceMessage::~BtPieceMessage()
  70. {
  71. delete [] rawData_;
  72. }
  73. void BtPieceMessage::setRawMessage(unsigned char* data)
  74. {
  75. delete [] rawData_;
  76. rawData_ = data;
  77. block_ = data+9;
  78. }
  79. BtPieceMessageHandle BtPieceMessage::create
  80. (const unsigned char* data, size_t dataLength)
  81. {
  82. bittorrent::assertPayloadLengthGreater(9, dataLength, NAME);
  83. bittorrent::assertID(ID, data, NAME);
  84. BtPieceMessageHandle message(new BtPieceMessage());
  85. message->setIndex(bittorrent::getIntParam(data, 1));
  86. message->setBegin(bittorrent::getIntParam(data, 5));
  87. message->setBlockLength(dataLength-9);
  88. return message;
  89. }
  90. void BtPieceMessage::doReceivedAction()
  91. {
  92. if(isMetadataGetMode()) {
  93. return;
  94. }
  95. RequestSlot slot = getBtMessageDispatcher()->getOutstandingRequest
  96. (index_, begin_, blockLength_);
  97. getPeer()->updateDownloadLength(blockLength_);
  98. if(!RequestSlot::isNull(slot)) {
  99. getPeer()->snubbing(false);
  100. SharedHandle<Piece> piece = getPieceStorage()->getPiece(index_);
  101. off_t offset = (off_t)index_*downloadContext_->getPieceLength()+begin_;
  102. A2_LOG_DEBUG(fmt(MSG_PIECE_RECEIVED,
  103. getCuid(),
  104. static_cast<unsigned long>(index_),
  105. begin_,
  106. blockLength_,
  107. static_cast<long long int>(offset),
  108. static_cast<unsigned long>(slot.getBlockIndex())));
  109. getPieceStorage()->getDiskAdaptor()->writeData
  110. (block_, blockLength_, offset);
  111. piece->completeBlock(slot.getBlockIndex());
  112. A2_LOG_DEBUG(fmt(MSG_PIECE_BITFIELD, getCuid(),
  113. util::toHex(piece->getBitfield(),
  114. piece->getBitfieldLength()).c_str()));
  115. piece->updateHash(begin_, block_, blockLength_);
  116. getBtMessageDispatcher()->removeOutstandingRequest(slot);
  117. if(piece->pieceComplete()) {
  118. if(checkPieceHash(piece)) {
  119. onNewPiece(piece);
  120. } else {
  121. onWrongPiece(piece);
  122. throw DL_ABORT_EX("Bad piece hash.");
  123. }
  124. }
  125. } else {
  126. A2_LOG_DEBUG(fmt("CUID#%lld - RequestSlot not found, index=%lu, begin=%u",
  127. getCuid(),
  128. static_cast<unsigned long>(index_),
  129. begin_));
  130. }
  131. }
  132. size_t BtPieceMessage::MESSAGE_HEADER_LENGTH = 13;
  133. unsigned char* BtPieceMessage::createMessageHeader()
  134. {
  135. /**
  136. * len --- 9+blockLength, 4bytes
  137. * id --- 7, 1byte
  138. * index --- index, 4bytes
  139. * begin --- begin, 4bytes
  140. * total: 13bytes
  141. */
  142. unsigned char* msgHeader = new unsigned char[MESSAGE_HEADER_LENGTH];
  143. bittorrent::createPeerMessageString(msgHeader, MESSAGE_HEADER_LENGTH,
  144. 9+blockLength_, ID);
  145. bittorrent::setIntParam(&msgHeader[5], index_);
  146. bittorrent::setIntParam(&msgHeader[9], begin_);
  147. return msgHeader;
  148. }
  149. size_t BtPieceMessage::getMessageHeaderLength()
  150. {
  151. return MESSAGE_HEADER_LENGTH;
  152. }
  153. void BtPieceMessage::send()
  154. {
  155. if(isInvalidate()) {
  156. return;
  157. }
  158. size_t writtenLength;
  159. if(!isSendingInProgress()) {
  160. A2_LOG_INFO(fmt(MSG_SEND_PEER_MESSAGE,
  161. getCuid(),
  162. getPeer()->getIPAddress().c_str(),
  163. getPeer()->getPort(),
  164. toString().c_str()));
  165. unsigned char* msgHdr = createMessageHeader();
  166. size_t msgHdrLen = getMessageHeaderLength();
  167. A2_LOG_DEBUG(fmt("msglength = %lu bytes",
  168. static_cast<unsigned long>(msgHdrLen+blockLength_)));
  169. getPeerConnection()->pushBytes(msgHdr, msgHdrLen);
  170. off_t pieceDataOffset =
  171. (off_t)index_*downloadContext_->getPieceLength()+begin_;
  172. pushPieceData(pieceDataOffset, blockLength_);
  173. }
  174. writtenLength = getPeerConnection()->sendPendingData();
  175. getPeer()->updateUploadLength(writtenLength);
  176. setSendingInProgress(!getPeerConnection()->sendBufferIsEmpty());
  177. }
  178. void BtPieceMessage::pushPieceData(off_t offset, size_t length) const
  179. {
  180. assert(length <= 16*1024);
  181. unsigned char* buf = new unsigned char[length];
  182. ssize_t r;
  183. try {
  184. r = getPieceStorage()->getDiskAdaptor()->readData(buf, length, offset);
  185. } catch(RecoverableException& e) {
  186. delete [] buf;
  187. throw;
  188. }
  189. if(r == static_cast<ssize_t>(length)) {
  190. getPeerConnection()->pushBytes(buf, length);
  191. } else {
  192. throw DL_ABORT_EX(EX_DATA_READ);
  193. }
  194. }
  195. std::string BtPieceMessage::toString() const
  196. {
  197. return strconcat(NAME, " index=", util::itos(index_), ", begin=",
  198. util::itos(begin_), ", length=", util::itos(blockLength_));
  199. }
  200. bool BtPieceMessage::checkPieceHash(const SharedHandle<Piece>& piece)
  201. {
  202. if(!getPieceStorage()->isEndGame() && piece->isHashCalculated()) {
  203. A2_LOG_DEBUG(fmt("Hash is available!! index=%lu",
  204. static_cast<unsigned long>(piece->getIndex())));
  205. return
  206. piece->getHashString()==downloadContext_->getPieceHash(piece->getIndex());
  207. } else {
  208. off_t offset = (off_t)piece->getIndex()*downloadContext_->getPieceLength();
  209. return message_digest::staticSHA1DigestHexDigest
  210. (getPieceStorage()->getDiskAdaptor(), offset, piece->getLength())
  211. == downloadContext_->getPieceHash(piece->getIndex());
  212. }
  213. }
  214. void BtPieceMessage::onNewPiece(const SharedHandle<Piece>& piece)
  215. {
  216. A2_LOG_INFO(fmt(MSG_GOT_NEW_PIECE,
  217. getCuid(),
  218. static_cast<unsigned long>(piece->getIndex())));
  219. getPieceStorage()->completePiece(piece);
  220. getPieceStorage()->advertisePiece(getCuid(), piece->getIndex());
  221. }
  222. void BtPieceMessage::onWrongPiece(const SharedHandle<Piece>& piece)
  223. {
  224. A2_LOG_INFO(fmt(MSG_GOT_WRONG_PIECE,
  225. getCuid(),
  226. static_cast<unsigned long>(piece->getIndex())));
  227. erasePieceOnDisk(piece);
  228. piece->clearAllBlock();
  229. piece->destroyHashContext();
  230. getBtRequestFactory()->removeTargetPiece(piece);
  231. }
  232. void BtPieceMessage::erasePieceOnDisk(const SharedHandle<Piece>& piece)
  233. {
  234. size_t BUFSIZE = 4096;
  235. unsigned char buf[BUFSIZE];
  236. memset(buf, 0, BUFSIZE);
  237. off_t offset = (off_t)piece->getIndex()*downloadContext_->getPieceLength();
  238. div_t res = div(piece->getLength(), BUFSIZE);
  239. for(int i = 0; i < res.quot; ++i) {
  240. getPieceStorage()->getDiskAdaptor()->writeData(buf, BUFSIZE, offset);
  241. offset += BUFSIZE;
  242. }
  243. if(res.rem > 0) {
  244. getPieceStorage()->getDiskAdaptor()->writeData(buf, res.rem, offset);
  245. }
  246. }
  247. void BtPieceMessage::onChokingEvent(const BtChokingEvent& event)
  248. {
  249. if(!isInvalidate() &&
  250. !isSendingInProgress() &&
  251. !getPeer()->isInAmAllowedIndexSet(index_)) {
  252. A2_LOG_DEBUG(fmt(MSG_REJECT_PIECE_CHOKED,
  253. getCuid(),
  254. static_cast<unsigned long>(index_),
  255. begin_,
  256. blockLength_));
  257. if(getPeer()->isFastExtensionEnabled()) {
  258. BtMessageHandle rej =
  259. getBtMessageFactory()->createRejectMessage
  260. (index_, begin_, blockLength_);
  261. getBtMessageDispatcher()->addMessageToQueue(rej);
  262. }
  263. setInvalidate(true);
  264. }
  265. }
  266. void BtPieceMessage::onCancelSendingPieceEvent
  267. (const BtCancelSendingPieceEvent& event)
  268. {
  269. if(!isInvalidate() &&
  270. !isSendingInProgress() &&
  271. index_ == event.getIndex() &&
  272. begin_ == event.getBegin() &&
  273. blockLength_ == event.getLength()) {
  274. A2_LOG_DEBUG(fmt(MSG_REJECT_PIECE_CANCEL,
  275. getCuid(),
  276. static_cast<unsigned long>(index_),
  277. begin_,
  278. blockLength_));
  279. if(getPeer()->isFastExtensionEnabled()) {
  280. BtMessageHandle rej =
  281. getBtMessageFactory()->createRejectMessage
  282. (index_, begin_, blockLength_);
  283. getBtMessageDispatcher()->addMessageToQueue(rej);
  284. }
  285. setInvalidate(true);
  286. }
  287. }
  288. void BtPieceMessage::setDownloadContext
  289. (const SharedHandle<DownloadContext>& downloadContext)
  290. {
  291. downloadContext_ = downloadContext;
  292. }
  293. } // namespace aria2