BtPieceMessage.cc 11 KB

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