BtPieceMessage.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. }
  123. }
  124. } else {
  125. if(getLogger()->debug()) {
  126. getLogger()->debug("CUID#%s - RequestSlot not found, index=%d, begin=%d",
  127. util::itos(getCuid()).c_str(), index_, begin_);
  128. }
  129. }
  130. }
  131. size_t BtPieceMessage::MESSAGE_HEADER_LENGTH = 13;
  132. unsigned char* BtPieceMessage::createMessageHeader()
  133. {
  134. /**
  135. * len --- 9+blockLength, 4bytes
  136. * id --- 7, 1byte
  137. * index --- index, 4bytes
  138. * begin --- begin, 4bytes
  139. * total: 13bytes
  140. */
  141. unsigned char* msgHeader = new unsigned char[MESSAGE_HEADER_LENGTH];
  142. bittorrent::createPeerMessageString(msgHeader, MESSAGE_HEADER_LENGTH,
  143. 9+blockLength_, ID);
  144. bittorrent::setIntParam(&msgHeader[5], index_);
  145. bittorrent::setIntParam(&msgHeader[9], begin_);
  146. return msgHeader;
  147. }
  148. size_t BtPieceMessage::getMessageHeaderLength()
  149. {
  150. return MESSAGE_HEADER_LENGTH;
  151. }
  152. void BtPieceMessage::send()
  153. {
  154. if(isInvalidate()) {
  155. return;
  156. }
  157. size_t writtenLength;
  158. if(!isSendingInProgress()) {
  159. if(getLogger()->info()) {
  160. getLogger()->info(MSG_SEND_PEER_MESSAGE,
  161. util::itos(getCuid()).c_str(),
  162. getPeer()->getIPAddress().c_str(),
  163. getPeer()->getPort(),
  164. toString().c_str());
  165. }
  166. unsigned char* msgHdr = createMessageHeader();
  167. size_t msgHdrLen = getMessageHeaderLength();
  168. if(getLogger()->debug()) {
  169. getLogger()->debug("msglength = %lu bytes",
  170. static_cast<unsigned long>(msgHdrLen+blockLength_));
  171. }
  172. getPeerConnection()->pushBytes(msgHdr, msgHdrLen);
  173. getPeerConnection()->sendPendingData();
  174. off_t pieceDataOffset =
  175. (off_t)index_*downloadContext_->getPieceLength()+begin_;
  176. writtenLength = sendPieceData(pieceDataOffset, blockLength_);
  177. } else {
  178. writtenLength = getPeerConnection()->sendPendingData();
  179. }
  180. getPeer()->updateUploadLength(writtenLength);
  181. setSendingInProgress(!getPeerConnection()->sendBufferIsEmpty());
  182. }
  183. size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const
  184. {
  185. assert(length <= 16*1024);
  186. unsigned char* buf = new unsigned char[length];
  187. ssize_t r;
  188. try {
  189. r = getPieceStorage()->getDiskAdaptor()->readData(buf, length, offset);
  190. } catch(RecoverableException& e) {
  191. delete [] buf;
  192. throw;
  193. }
  194. if(r == static_cast<ssize_t>(length)) {
  195. getPeerConnection()->pushBytes(buf, length);
  196. return getPeerConnection()->sendPendingData();
  197. } else {
  198. throw DL_ABORT_EX(EX_DATA_READ);
  199. }
  200. }
  201. std::string BtPieceMessage::toString() const
  202. {
  203. return strconcat(NAME, " index=", util::itos(index_), ", begin=",
  204. util::itos(begin_), ", length=", util::itos(blockLength_));
  205. }
  206. bool BtPieceMessage::checkPieceHash(const SharedHandle<Piece>& piece)
  207. {
  208. if(piece->isHashCalculated()) {
  209. if(getLogger()->debug()) {
  210. getLogger()->debug("Hash is available!! index=%lu",
  211. static_cast<unsigned long>(piece->getIndex()));
  212. }
  213. return
  214. piece->getHashString()==downloadContext_->getPieceHash(piece->getIndex());
  215. } else {
  216. off_t offset = (off_t)piece->getIndex()*downloadContext_->getPieceLength();
  217. return MessageDigestHelper::staticSHA1Digest
  218. (getPieceStorage()->getDiskAdaptor(), offset, piece->getLength())
  219. == downloadContext_->getPieceHash(piece->getIndex());
  220. }
  221. }
  222. void BtPieceMessage::onNewPiece(const SharedHandle<Piece>& piece)
  223. {
  224. if(getLogger()->info()) {
  225. getLogger()->info(MSG_GOT_NEW_PIECE,
  226. util::itos(getCuid()).c_str(), piece->getIndex());
  227. }
  228. getPieceStorage()->completePiece(piece);
  229. getPieceStorage()->advertisePiece(getCuid(), piece->getIndex());
  230. }
  231. void BtPieceMessage::onWrongPiece(const SharedHandle<Piece>& piece)
  232. {
  233. if(getLogger()->info()) {
  234. getLogger()->info(MSG_GOT_WRONG_PIECE,
  235. util::itos(getCuid()).c_str(), piece->getIndex());
  236. }
  237. erasePieceOnDisk(piece);
  238. piece->clearAllBlock();
  239. piece->destroyHashContext();
  240. getBtRequestFactory()->removeTargetPiece(piece);
  241. }
  242. void BtPieceMessage::erasePieceOnDisk(const SharedHandle<Piece>& piece)
  243. {
  244. size_t BUFSIZE = 4096;
  245. unsigned char buf[BUFSIZE];
  246. memset(buf, 0, BUFSIZE);
  247. off_t offset = (off_t)piece->getIndex()*downloadContext_->getPieceLength();
  248. div_t res = div(piece->getLength(), BUFSIZE);
  249. for(int i = 0; i < res.quot; ++i) {
  250. getPieceStorage()->getDiskAdaptor()->writeData(buf, BUFSIZE, offset);
  251. offset += BUFSIZE;
  252. }
  253. if(res.rem > 0) {
  254. getPieceStorage()->getDiskAdaptor()->writeData(buf, res.rem, offset);
  255. }
  256. }
  257. void BtPieceMessage::onChokingEvent(const BtChokingEvent& event)
  258. {
  259. if(!isInvalidate() &&
  260. !isSendingInProgress() &&
  261. !getPeer()->isInAmAllowedIndexSet(index_)) {
  262. if(getLogger()->debug()) {
  263. getLogger()->debug(MSG_REJECT_PIECE_CHOKED,
  264. util::itos(getCuid()).c_str(),
  265. index_, begin_, blockLength_);
  266. }
  267. if(getPeer()->isFastExtensionEnabled()) {
  268. BtMessageHandle rej =
  269. getBtMessageFactory()->createRejectMessage
  270. (index_, begin_, blockLength_);
  271. getBtMessageDispatcher()->addMessageToQueue(rej);
  272. }
  273. setInvalidate(true);
  274. }
  275. }
  276. void BtPieceMessage::onCancelSendingPieceEvent
  277. (const BtCancelSendingPieceEvent& event)
  278. {
  279. if(!isInvalidate() &&
  280. !isSendingInProgress() &&
  281. index_ == event.getIndex() &&
  282. begin_ == event.getBegin() &&
  283. blockLength_ == event.getLength()) {
  284. if(getLogger()->debug()) {
  285. getLogger()->debug(MSG_REJECT_PIECE_CANCEL,
  286. util::itos(getCuid()).c_str(),
  287. index_, begin_, blockLength_);
  288. }
  289. if(getPeer()->isFastExtensionEnabled()) {
  290. BtMessageHandle rej =
  291. getBtMessageFactory()->createRejectMessage
  292. (index_, begin_, blockLength_);
  293. getBtMessageDispatcher()->addMessageToQueue(rej);
  294. }
  295. setInvalidate(true);
  296. }
  297. }
  298. void BtPieceMessage::setDownloadContext
  299. (const SharedHandle<DownloadContext>& downloadContext)
  300. {
  301. downloadContext_ = downloadContext;
  302. }
  303. } // namespace aria2