BtPieceMessage.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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()->ipaddr.c_str(), getPeer()->port,
  163. toString().c_str());
  164. }
  165. unsigned char* msgHdr = createMessageHeader();
  166. size_t msgHdrLen = getMessageHeaderLength();
  167. if(getLogger()->debug()) {
  168. getLogger()->debug("msglength = %lu bytes",
  169. static_cast<unsigned long>(msgHdrLen+_blockLength));
  170. }
  171. getPeerConnection()->pushBytes(msgHdr, msgHdrLen);
  172. getPeerConnection()->sendPendingData();
  173. off_t pieceDataOffset =
  174. (off_t)_index*_downloadContext->getPieceLength()+_begin;
  175. writtenLength = sendPieceData(pieceDataOffset, _blockLength);
  176. } else {
  177. writtenLength = getPeerConnection()->sendPendingData();
  178. }
  179. getPeer()->updateUploadLength(writtenLength);
  180. setSendingInProgress(!getPeerConnection()->sendBufferIsEmpty());
  181. }
  182. size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const
  183. {
  184. assert(length <= 16*1024);
  185. unsigned char* buf = new unsigned char[length];
  186. ssize_t r;
  187. try {
  188. r = getPieceStorage()->getDiskAdaptor()->readData(buf, length, offset);
  189. } catch(RecoverableException& e) {
  190. delete [] buf;
  191. throw;
  192. }
  193. if(r == static_cast<ssize_t>(length)) {
  194. getPeerConnection()->pushBytes(buf, length);
  195. return getPeerConnection()->sendPendingData();
  196. } else {
  197. throw DL_ABORT_EX(EX_DATA_READ);
  198. }
  199. }
  200. std::string BtPieceMessage::toString() const
  201. {
  202. return strconcat(NAME, " index=", util::itos(_index), ", begin=",
  203. util::itos(_begin), ", length=", util::itos(_blockLength));
  204. }
  205. bool BtPieceMessage::checkPieceHash(const SharedHandle<Piece>& piece)
  206. {
  207. if(piece->isHashCalculated()) {
  208. if(getLogger()->debug()) {
  209. getLogger()->debug("Hash is available!! index=%lu",
  210. static_cast<unsigned long>(piece->getIndex()));
  211. }
  212. return
  213. piece->getHashString()==_downloadContext->getPieceHash(piece->getIndex());
  214. } else {
  215. off_t offset = (off_t)piece->getIndex()*_downloadContext->getPieceLength();
  216. return MessageDigestHelper::staticSHA1Digest
  217. (getPieceStorage()->getDiskAdaptor(), offset, piece->getLength())
  218. == _downloadContext->getPieceHash(piece->getIndex());
  219. }
  220. }
  221. void BtPieceMessage::onNewPiece(const SharedHandle<Piece>& piece)
  222. {
  223. if(getLogger()->info()) {
  224. getLogger()->info(MSG_GOT_NEW_PIECE,
  225. util::itos(getCuid()).c_str(), piece->getIndex());
  226. }
  227. getPieceStorage()->completePiece(piece);
  228. getPieceStorage()->advertisePiece(getCuid(), piece->getIndex());
  229. }
  230. void BtPieceMessage::onWrongPiece(const SharedHandle<Piece>& piece)
  231. {
  232. if(getLogger()->info()) {
  233. getLogger()->info(MSG_GOT_WRONG_PIECE,
  234. util::itos(getCuid()).c_str(), piece->getIndex());
  235. }
  236. erasePieceOnDisk(piece);
  237. piece->clearAllBlock();
  238. piece->destroyHashContext();
  239. getBtRequestFactory()->removeTargetPiece(piece);
  240. }
  241. void BtPieceMessage::erasePieceOnDisk(const SharedHandle<Piece>& piece)
  242. {
  243. size_t BUFSIZE = 4096;
  244. unsigned char buf[BUFSIZE];
  245. memset(buf, 0, BUFSIZE);
  246. off_t offset = (off_t)piece->getIndex()*_downloadContext->getPieceLength();
  247. div_t res = div(piece->getLength(), BUFSIZE);
  248. for(int i = 0; i < res.quot; ++i) {
  249. getPieceStorage()->getDiskAdaptor()->writeData(buf, BUFSIZE, offset);
  250. offset += BUFSIZE;
  251. }
  252. if(res.rem > 0) {
  253. getPieceStorage()->getDiskAdaptor()->writeData(buf, res.rem, offset);
  254. }
  255. }
  256. void BtPieceMessage::onChokingEvent(const BtChokingEvent& event)
  257. {
  258. if(!isInvalidate() &&
  259. !isSendingInProgress() &&
  260. !getPeer()->isInAmAllowedIndexSet(_index)) {
  261. if(getLogger()->debug()) {
  262. getLogger()->debug(MSG_REJECT_PIECE_CHOKED,
  263. util::itos(getCuid()).c_str(),
  264. _index, _begin, _blockLength);
  265. }
  266. if(getPeer()->isFastExtensionEnabled()) {
  267. BtMessageHandle rej =
  268. getBtMessageFactory()->createRejectMessage
  269. (_index, _begin, _blockLength);
  270. getBtMessageDispatcher()->addMessageToQueue(rej);
  271. }
  272. setInvalidate(true);
  273. }
  274. }
  275. void BtPieceMessage::onCancelSendingPieceEvent
  276. (const BtCancelSendingPieceEvent& event)
  277. {
  278. if(!isInvalidate() &&
  279. !isSendingInProgress() &&
  280. _index == event.getIndex() &&
  281. _begin == event.getBegin() &&
  282. _blockLength == event.getLength()) {
  283. if(getLogger()->debug()) {
  284. getLogger()->debug(MSG_REJECT_PIECE_CANCEL,
  285. util::itos(getCuid()).c_str(),
  286. _index, _begin, _blockLength);
  287. }
  288. if(getPeer()->isFastExtensionEnabled()) {
  289. BtMessageHandle rej =
  290. getBtMessageFactory()->createRejectMessage
  291. (_index, _begin, _blockLength);
  292. getBtMessageDispatcher()->addMessageToQueue(rej);
  293. }
  294. setInvalidate(true);
  295. }
  296. }
  297. void BtPieceMessage::setDownloadContext
  298. (const SharedHandle<DownloadContext>& downloadContext)
  299. {
  300. _downloadContext = downloadContext;
  301. }
  302. } // namespace aria2