BtPieceMessage.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. BtPieceMessage::BtPieceMessage
  58. (size_t index, uint32_t begin, size_t blockLength):
  59. AbstractBtMessage(ID, NAME),
  60. index_(index),
  61. begin_(begin),
  62. blockLength_(blockLength),
  63. block_(0),
  64. rawData_(0)
  65. {
  66. setUploading(true);
  67. }
  68. BtPieceMessage::~BtPieceMessage()
  69. {
  70. delete [] rawData_;
  71. }
  72. void BtPieceMessage::setRawMessage(unsigned char* data)
  73. {
  74. delete [] rawData_;
  75. rawData_ = data;
  76. block_ = data+9;
  77. }
  78. BtPieceMessageHandle BtPieceMessage::create
  79. (const unsigned char* data, size_t dataLength)
  80. {
  81. bittorrent::assertPayloadLengthGreater(9, dataLength, NAME);
  82. bittorrent::assertID(ID, data, NAME);
  83. BtPieceMessageHandle message(new BtPieceMessage());
  84. message->setIndex(bittorrent::getIntParam(data, 1));
  85. message->setBegin(bittorrent::getIntParam(data, 5));
  86. message->setBlockLength(dataLength-9);
  87. return message;
  88. }
  89. void BtPieceMessage::doReceivedAction()
  90. {
  91. if(isMetadataGetMode()) {
  92. return;
  93. }
  94. RequestSlot slot = getBtMessageDispatcher()->getOutstandingRequest
  95. (index_, begin_, blockLength_);
  96. getPeer()->updateDownloadLength(blockLength_);
  97. if(!RequestSlot::isNull(slot)) {
  98. getPeer()->snubbing(false);
  99. SharedHandle<Piece> piece = getPieceStorage()->getPiece(index_);
  100. off_t offset = (off_t)index_*downloadContext_->getPieceLength()+begin_;
  101. if(getLogger()->debug()) {
  102. getLogger()->debug(MSG_PIECE_RECEIVED,
  103. util::itos(getCuid()).c_str(),
  104. index_, begin_, blockLength_, offset,
  105. slot.getBlockIndex());
  106. }
  107. getPieceStorage()->getDiskAdaptor()->writeData
  108. (block_, blockLength_, offset);
  109. piece->completeBlock(slot.getBlockIndex());
  110. if(getLogger()->debug()) {
  111. getLogger()->debug(MSG_PIECE_BITFIELD, util::itos(getCuid()).c_str(),
  112. util::toHex(piece->getBitfield(),
  113. piece->getBitfieldLength()).c_str());
  114. }
  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. if(getLogger()->debug()) {
  127. getLogger()->debug("CUID#%s - RequestSlot not found, index=%d, begin=%d",
  128. util::itos(getCuid()).c_str(), index_, begin_);
  129. }
  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. if(getLogger()->info()) {
  161. getLogger()->info(MSG_SEND_PEER_MESSAGE,
  162. util::itos(getCuid()).c_str(),
  163. getPeer()->getIPAddress().c_str(),
  164. getPeer()->getPort(),
  165. toString().c_str());
  166. }
  167. unsigned char* msgHdr = createMessageHeader();
  168. size_t msgHdrLen = getMessageHeaderLength();
  169. if(getLogger()->debug()) {
  170. getLogger()->debug("msglength = %lu bytes",
  171. static_cast<unsigned long>(msgHdrLen+blockLength_));
  172. }
  173. getPeerConnection()->pushBytes(msgHdr, msgHdrLen);
  174. getPeerConnection()->sendPendingData();
  175. off_t pieceDataOffset =
  176. (off_t)index_*downloadContext_->getPieceLength()+begin_;
  177. writtenLength = sendPieceData(pieceDataOffset, blockLength_);
  178. } else {
  179. writtenLength = getPeerConnection()->sendPendingData();
  180. }
  181. getPeer()->updateUploadLength(writtenLength);
  182. setSendingInProgress(!getPeerConnection()->sendBufferIsEmpty());
  183. }
  184. size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const
  185. {
  186. assert(length <= 16*1024);
  187. unsigned char* buf = new unsigned char[length];
  188. ssize_t r;
  189. try {
  190. r = getPieceStorage()->getDiskAdaptor()->readData(buf, length, offset);
  191. } catch(RecoverableException& e) {
  192. delete [] buf;
  193. throw;
  194. }
  195. if(r == static_cast<ssize_t>(length)) {
  196. getPeerConnection()->pushBytes(buf, length);
  197. return getPeerConnection()->sendPendingData();
  198. } else {
  199. throw DL_ABORT_EX(EX_DATA_READ);
  200. }
  201. }
  202. std::string BtPieceMessage::toString() const
  203. {
  204. return strconcat(NAME, " index=", util::itos(index_), ", begin=",
  205. util::itos(begin_), ", length=", util::itos(blockLength_));
  206. }
  207. bool BtPieceMessage::checkPieceHash(const SharedHandle<Piece>& piece)
  208. {
  209. if(!getPieceStorage()->isEndGame() && piece->isHashCalculated()) {
  210. if(getLogger()->debug()) {
  211. getLogger()->debug("Hash is available!! index=%lu",
  212. static_cast<unsigned long>(piece->getIndex()));
  213. }
  214. return
  215. piece->getHashString()==downloadContext_->getPieceHash(piece->getIndex());
  216. } else {
  217. off_t offset = (off_t)piece->getIndex()*downloadContext_->getPieceLength();
  218. return MessageDigestHelper::staticSHA1Digest
  219. (getPieceStorage()->getDiskAdaptor(), offset, piece->getLength())
  220. == downloadContext_->getPieceHash(piece->getIndex());
  221. }
  222. }
  223. void BtPieceMessage::onNewPiece(const SharedHandle<Piece>& piece)
  224. {
  225. if(getLogger()->info()) {
  226. getLogger()->info(MSG_GOT_NEW_PIECE,
  227. util::itos(getCuid()).c_str(), piece->getIndex());
  228. }
  229. getPieceStorage()->completePiece(piece);
  230. getPieceStorage()->advertisePiece(getCuid(), piece->getIndex());
  231. }
  232. void BtPieceMessage::onWrongPiece(const SharedHandle<Piece>& piece)
  233. {
  234. if(getLogger()->info()) {
  235. getLogger()->info(MSG_GOT_WRONG_PIECE,
  236. util::itos(getCuid()).c_str(), piece->getIndex());
  237. }
  238. erasePieceOnDisk(piece);
  239. piece->clearAllBlock();
  240. piece->destroyHashContext();
  241. getBtRequestFactory()->removeTargetPiece(piece);
  242. }
  243. void BtPieceMessage::erasePieceOnDisk(const SharedHandle<Piece>& piece)
  244. {
  245. size_t BUFSIZE = 4096;
  246. unsigned char buf[BUFSIZE];
  247. memset(buf, 0, BUFSIZE);
  248. off_t offset = (off_t)piece->getIndex()*downloadContext_->getPieceLength();
  249. div_t res = div(piece->getLength(), BUFSIZE);
  250. for(int i = 0; i < res.quot; ++i) {
  251. getPieceStorage()->getDiskAdaptor()->writeData(buf, BUFSIZE, offset);
  252. offset += BUFSIZE;
  253. }
  254. if(res.rem > 0) {
  255. getPieceStorage()->getDiskAdaptor()->writeData(buf, res.rem, offset);
  256. }
  257. }
  258. void BtPieceMessage::onChokingEvent(const BtChokingEvent& event)
  259. {
  260. if(!isInvalidate() &&
  261. !isSendingInProgress() &&
  262. !getPeer()->isInAmAllowedIndexSet(index_)) {
  263. if(getLogger()->debug()) {
  264. getLogger()->debug(MSG_REJECT_PIECE_CHOKED,
  265. util::itos(getCuid()).c_str(),
  266. index_, begin_, blockLength_);
  267. }
  268. if(getPeer()->isFastExtensionEnabled()) {
  269. BtMessageHandle rej =
  270. getBtMessageFactory()->createRejectMessage
  271. (index_, begin_, blockLength_);
  272. getBtMessageDispatcher()->addMessageToQueue(rej);
  273. }
  274. setInvalidate(true);
  275. }
  276. }
  277. void BtPieceMessage::onCancelSendingPieceEvent
  278. (const BtCancelSendingPieceEvent& event)
  279. {
  280. if(!isInvalidate() &&
  281. !isSendingInProgress() &&
  282. index_ == event.getIndex() &&
  283. begin_ == event.getBegin() &&
  284. blockLength_ == event.getLength()) {
  285. if(getLogger()->debug()) {
  286. getLogger()->debug(MSG_REJECT_PIECE_CANCEL,
  287. util::itos(getCuid()).c_str(),
  288. index_, begin_, blockLength_);
  289. }
  290. if(getPeer()->isFastExtensionEnabled()) {
  291. BtMessageHandle rej =
  292. getBtMessageFactory()->createRejectMessage
  293. (index_, begin_, blockLength_);
  294. getBtMessageDispatcher()->addMessageToQueue(rej);
  295. }
  296. setInvalidate(true);
  297. }
  298. }
  299. void BtPieceMessage::setDownloadContext
  300. (const SharedHandle<DownloadContext>& downloadContext)
  301. {
  302. downloadContext_ = downloadContext;
  303. }
  304. } // namespace aria2