BtPieceMessage.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. #include "PeerStorage.h"
  57. #include "array_fun.h"
  58. #include "WrDiskCache.h"
  59. #include "WrDiskCacheEntry.h"
  60. #include "DownloadFailureException.h"
  61. #include "BtRejectMessage.h"
  62. namespace aria2 {
  63. const char BtPieceMessage::NAME[] = "piece";
  64. BtPieceMessage::BtPieceMessage(size_t index, int32_t begin, int32_t blockLength)
  65. : AbstractBtMessage(ID, NAME),
  66. index_(index),
  67. begin_(begin),
  68. blockLength_(blockLength),
  69. data_(nullptr),
  70. downloadContext_(nullptr),
  71. peerStorage_(nullptr)
  72. {
  73. setUploading(true);
  74. }
  75. BtPieceMessage::~BtPieceMessage() {}
  76. void BtPieceMessage::setMsgPayload(const unsigned char* data) { data_ = data; }
  77. std::unique_ptr<BtPieceMessage>
  78. BtPieceMessage::create(const unsigned char* data, size_t dataLength)
  79. {
  80. bittorrent::assertPayloadLengthGreater(9, dataLength, NAME);
  81. bittorrent::assertID(ID, data, NAME);
  82. return make_unique<BtPieceMessage>(bittorrent::getIntParam(data, 1),
  83. bittorrent::getIntParam(data, 5),
  84. dataLength - 9);
  85. }
  86. void BtPieceMessage::doReceivedAction()
  87. {
  88. if (isMetadataGetMode()) {
  89. return;
  90. }
  91. auto slot = getBtMessageDispatcher()->getOutstandingRequest(index_, begin_,
  92. blockLength_);
  93. getPeer()->updateDownload(blockLength_);
  94. downloadContext_->updateDownload(blockLength_);
  95. if (slot) {
  96. getPeer()->snubbing(false);
  97. std::shared_ptr<Piece> piece = getPieceStorage()->getPiece(index_);
  98. int64_t offset =
  99. static_cast<int64_t>(index_) * downloadContext_->getPieceLength() +
  100. begin_;
  101. A2_LOG_DEBUG(fmt(MSG_PIECE_RECEIVED, getCuid(),
  102. static_cast<unsigned long>(index_), begin_, blockLength_,
  103. static_cast<int64_t>(offset),
  104. static_cast<unsigned long>(slot->getBlockIndex())));
  105. if (piece->hasBlock(slot->getBlockIndex())) {
  106. A2_LOG_DEBUG("Already have this block.");
  107. return;
  108. }
  109. if (piece->getWrDiskCacheEntry()) {
  110. // Write Disk Cache enabled. Unfortunately, it incurs extra data
  111. // copy.
  112. auto dataCopy = new unsigned char[blockLength_];
  113. memcpy(dataCopy, data_ + 9, blockLength_);
  114. piece->updateWrCache(getPieceStorage()->getWrDiskCache(), dataCopy, 0,
  115. blockLength_, blockLength_, offset);
  116. }
  117. else {
  118. getPieceStorage()->getDiskAdaptor()->writeData(data_ + 9, blockLength_,
  119. offset);
  120. }
  121. piece->completeBlock(slot->getBlockIndex());
  122. A2_LOG_DEBUG(fmt(
  123. MSG_PIECE_BITFIELD, getCuid(),
  124. util::toHex(piece->getBitfield(), piece->getBitfieldLength()).c_str()));
  125. piece->updateHash(begin_, data_ + 9, blockLength_);
  126. getBtMessageDispatcher()->removeOutstandingRequest(slot);
  127. if (piece->pieceComplete()) {
  128. if (checkPieceHash(piece)) {
  129. onNewPiece(piece);
  130. }
  131. else {
  132. onWrongPiece(piece);
  133. peerStorage_->addBadPeer(getPeer()->getIPAddress());
  134. throw DL_ABORT_EX("Bad piece hash.");
  135. }
  136. }
  137. }
  138. else {
  139. A2_LOG_DEBUG(fmt("CUID#%" PRId64
  140. " - RequestSlot not found, index=%lu, begin=%d",
  141. getCuid(), static_cast<unsigned long>(index_), begin_));
  142. }
  143. }
  144. size_t BtPieceMessage::MESSAGE_HEADER_LENGTH = 13;
  145. void BtPieceMessage::createMessageHeader(unsigned char* msgHeader) const
  146. {
  147. /**
  148. * len --- 9+blockLength, 4bytes
  149. * id --- 7, 1byte
  150. * index --- index, 4bytes
  151. * begin --- begin, 4bytes
  152. * total: 13bytes
  153. */
  154. bittorrent::createPeerMessageString(msgHeader, MESSAGE_HEADER_LENGTH,
  155. 9 + blockLength_, ID);
  156. bittorrent::setIntParam(&msgHeader[5], index_);
  157. bittorrent::setIntParam(&msgHeader[9], begin_);
  158. }
  159. size_t BtPieceMessage::getMessageHeaderLength()
  160. {
  161. return MESSAGE_HEADER_LENGTH;
  162. }
  163. namespace {
  164. struct PieceSendUpdate : public ProgressUpdate {
  165. PieceSendUpdate(DownloadContext* dctx, std::shared_ptr<Peer> peer,
  166. size_t headerLength)
  167. : dctx(dctx), peer(std::move(peer)), headerLength(headerLength)
  168. {
  169. }
  170. virtual void update(size_t length, bool complete) CXX11_OVERRIDE
  171. {
  172. if (headerLength > 0) {
  173. size_t m = std::min(headerLength, length);
  174. headerLength -= m;
  175. length -= m;
  176. }
  177. peer->updateUploadLength(length);
  178. dctx->updateUploadLength(length);
  179. }
  180. DownloadContext* dctx;
  181. std::shared_ptr<Peer> peer;
  182. size_t headerLength;
  183. };
  184. } // namespace
  185. void BtPieceMessage::send()
  186. {
  187. if (isInvalidate()) {
  188. return;
  189. }
  190. A2_LOG_INFO(fmt(MSG_SEND_PEER_MESSAGE, getCuid(),
  191. getPeer()->getIPAddress().c_str(), getPeer()->getPort(),
  192. toString().c_str()));
  193. int64_t pieceDataOffset =
  194. static_cast<int64_t>(index_) * downloadContext_->getPieceLength() +
  195. begin_;
  196. pushPieceData(pieceDataOffset, blockLength_);
  197. }
  198. void BtPieceMessage::pushPieceData(int64_t offset, int32_t length) const
  199. {
  200. assert(length <= static_cast<int32_t>(16_k));
  201. auto buf = make_unique<unsigned char[]>(length + MESSAGE_HEADER_LENGTH);
  202. createMessageHeader(buf.get());
  203. ssize_t r;
  204. r = getPieceStorage()->getDiskAdaptor()->readData(
  205. buf.get() + MESSAGE_HEADER_LENGTH, length, offset);
  206. if (r == length) {
  207. const auto& peer = getPeer();
  208. getPeerConnection()->pushBytes(
  209. buf.release(), length + MESSAGE_HEADER_LENGTH,
  210. make_unique<PieceSendUpdate>(downloadContext_, peer,
  211. MESSAGE_HEADER_LENGTH));
  212. peer->updateUploadSpeed(length);
  213. downloadContext_->updateUploadSpeed(length);
  214. }
  215. else {
  216. throw DL_ABORT_EX(EX_DATA_READ);
  217. }
  218. }
  219. std::string BtPieceMessage::toString() const
  220. {
  221. return fmt("%s index=%lu, begin=%d, length=%d", NAME,
  222. static_cast<unsigned long>(index_), begin_, blockLength_);
  223. }
  224. bool BtPieceMessage::checkPieceHash(const std::shared_ptr<Piece>& piece)
  225. {
  226. if (!getPieceStorage()->isEndGame() && piece->isHashCalculated()) {
  227. A2_LOG_DEBUG(fmt("Hash is available!! index=%lu",
  228. static_cast<unsigned long>(piece->getIndex())));
  229. return piece->getDigest() ==
  230. downloadContext_->getPieceHash(piece->getIndex());
  231. }
  232. else {
  233. A2_LOG_DEBUG(fmt("Calculating hash index=%lu",
  234. static_cast<unsigned long>(piece->getIndex())));
  235. try {
  236. return piece->getDigestWithWrCache(downloadContext_->getPieceLength(),
  237. getPieceStorage()->getDiskAdaptor()) ==
  238. downloadContext_->getPieceHash(piece->getIndex());
  239. }
  240. catch (RecoverableException& e) {
  241. piece->clearAllBlock(getPieceStorage()->getWrDiskCache());
  242. throw;
  243. }
  244. }
  245. }
  246. void BtPieceMessage::onNewPiece(const std::shared_ptr<Piece>& piece)
  247. {
  248. if (piece->getWrDiskCacheEntry()) {
  249. // We flush cached data whenever an whole piece is retrieved.
  250. piece->flushWrCache(getPieceStorage()->getWrDiskCache());
  251. if (piece->getWrDiskCacheEntry()->getError() !=
  252. WrDiskCacheEntry::CACHE_ERR_SUCCESS) {
  253. piece->clearAllBlock(getPieceStorage()->getWrDiskCache());
  254. throw DOWNLOAD_FAILURE_EXCEPTION2(
  255. fmt("Write disk cache flush failure index=%lu",
  256. static_cast<unsigned long>(piece->getIndex())),
  257. piece->getWrDiskCacheEntry()->getErrorCode());
  258. }
  259. }
  260. A2_LOG_INFO(fmt(MSG_GOT_NEW_PIECE, getCuid(),
  261. static_cast<unsigned long>(piece->getIndex())));
  262. getPieceStorage()->completePiece(piece);
  263. getPieceStorage()->advertisePiece(getCuid(), piece->getIndex());
  264. }
  265. void BtPieceMessage::onWrongPiece(const std::shared_ptr<Piece>& piece)
  266. {
  267. A2_LOG_INFO(fmt(MSG_GOT_WRONG_PIECE, getCuid(),
  268. static_cast<unsigned long>(piece->getIndex())));
  269. piece->clearAllBlock(getPieceStorage()->getWrDiskCache());
  270. piece->destroyHashContext();
  271. getBtRequestFactory()->removeTargetPiece(piece);
  272. }
  273. void BtPieceMessage::onChokingEvent(const BtChokingEvent& event)
  274. {
  275. if (!isInvalidate() && !getPeer()->isInAmAllowedIndexSet(index_)) {
  276. A2_LOG_DEBUG(fmt(MSG_REJECT_PIECE_CHOKED, getCuid(),
  277. static_cast<unsigned long>(index_), begin_, blockLength_));
  278. if (getPeer()->isFastExtensionEnabled()) {
  279. getBtMessageDispatcher()->addMessageToQueue(
  280. getBtMessageFactory()->createRejectMessage(index_, begin_,
  281. blockLength_));
  282. }
  283. setInvalidate(true);
  284. }
  285. }
  286. void BtPieceMessage::onCancelSendingPieceEvent(
  287. const BtCancelSendingPieceEvent& event)
  288. {
  289. if (!isInvalidate() && index_ == event.getIndex() &&
  290. begin_ == event.getBegin() && blockLength_ == event.getLength()) {
  291. A2_LOG_DEBUG(fmt(MSG_REJECT_PIECE_CANCEL, getCuid(),
  292. static_cast<unsigned long>(index_), begin_, blockLength_));
  293. if (getPeer()->isFastExtensionEnabled()) {
  294. getBtMessageDispatcher()->addMessageToQueue(
  295. getBtMessageFactory()->createRejectMessage(index_, begin_,
  296. blockLength_));
  297. }
  298. setInvalidate(true);
  299. }
  300. }
  301. void BtPieceMessage::setDownloadContext(DownloadContext* downloadContext)
  302. {
  303. downloadContext_ = downloadContext;
  304. }
  305. void BtPieceMessage::setPeerStorage(PeerStorage* peerStorage)
  306. {
  307. peerStorage_ = peerStorage;
  308. }
  309. } // namespace aria2