BtPieceMessage.cc 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 "PeerMessageUtil.h"
  37. #include "Util.h"
  38. #include "message.h"
  39. #include "DlAbortEx.h"
  40. #include "BtChokingEvent.h"
  41. #include "BtCancelSendingPieceEvent.h"
  42. #include "MessageDigestHelper.h"
  43. #include "DiskAdaptor.h"
  44. #include "Logger.h"
  45. #include "Peer.h"
  46. #include "Piece.h"
  47. #include "BtContext.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 <cstring>
  55. namespace aria2 {
  56. void BtPieceMessage::setBlock(const unsigned char* block, size_t blockLength) {
  57. delete [] this->block;
  58. this->blockLength = blockLength;
  59. this->block = new unsigned char[this->blockLength];
  60. memcpy(this->block, block, this->blockLength);
  61. }
  62. BtPieceMessageHandle BtPieceMessage::create(const unsigned char* data, size_t dataLength) {
  63. if(dataLength <= 9) {
  64. throw DlAbortEx
  65. (StringFormat(EX_INVALID_PAYLOAD_SIZE, "piece", dataLength, 9).str());
  66. }
  67. uint8_t id = PeerMessageUtil::getId(data);
  68. if(id != ID) {
  69. throw DlAbortEx
  70. (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "piece", ID).str());
  71. }
  72. BtPieceMessageHandle message(new BtPieceMessage());
  73. message->setIndex(PeerMessageUtil::getIntParam(data, 1));
  74. message->setBegin(PeerMessageUtil::getIntParam(data, 5));
  75. message->setBlock(data+9, dataLength-9);
  76. return message;
  77. }
  78. void BtPieceMessage::doReceivedAction() {
  79. RequestSlot slot = dispatcher->getOutstandingRequest(index,
  80. begin,
  81. blockLength);
  82. peer->updateDownloadLength(blockLength);
  83. if(!RequestSlot::isNull(slot)) {
  84. peer->snubbing(false);
  85. peer->updateLatency(slot.getLatencyInMillis());
  86. PieceHandle piece = pieceStorage->getPiece(index);
  87. off_t offset = (off_t)index*btContext->getPieceLength()+begin;
  88. logger->debug(MSG_PIECE_RECEIVED,
  89. cuid, index, begin, blockLength, offset, slot.getBlockIndex());
  90. pieceStorage->getDiskAdaptor()->writeData(block, blockLength, offset);
  91. piece->completeBlock(slot.getBlockIndex());
  92. logger->debug(MSG_PIECE_BITFIELD, cuid,
  93. Util::toHex(piece->getBitfield(),
  94. piece->getBitfieldLength()).c_str());
  95. dispatcher->removeOutstandingRequest(slot);
  96. if(piece->pieceComplete()) {
  97. if(checkPieceHash(piece)) {
  98. onNewPiece(piece);
  99. } else {
  100. onWrongPiece(piece);
  101. }
  102. }
  103. } else {
  104. logger->debug("CUID#%d - RequestSlot not found, index=%d, begin=%d",
  105. cuid, index, begin);
  106. }
  107. }
  108. size_t BtPieceMessage::MESSAGE_HEADER_LENGTH = 13;
  109. const unsigned char* BtPieceMessage::getMessageHeader() {
  110. if(!msgHeader) {
  111. /**
  112. * len --- 9+blockLength, 4bytes
  113. * id --- 7, 1byte
  114. * index --- index, 4bytes
  115. * begin --- begin, 4bytes
  116. * total: 13bytes
  117. */
  118. msgHeader = new unsigned char[MESSAGE_HEADER_LENGTH];
  119. PeerMessageUtil::createPeerMessageString(msgHeader, MESSAGE_HEADER_LENGTH,
  120. 9+blockLength, ID);
  121. PeerMessageUtil::setIntParam(&msgHeader[5], index);
  122. PeerMessageUtil::setIntParam(&msgHeader[9], begin);
  123. }
  124. return msgHeader;
  125. }
  126. size_t BtPieceMessage::getMessageHeaderLength() {
  127. return MESSAGE_HEADER_LENGTH;
  128. }
  129. void BtPieceMessage::send() {
  130. if(invalidate) {
  131. return;
  132. }
  133. if(!headerSent) {
  134. if(!sendingInProgress) {
  135. logger->info(MSG_SEND_PEER_MESSAGE,
  136. cuid, peer->ipaddr.c_str(), peer->port,
  137. toString().c_str());
  138. getMessageHeader();
  139. leftDataLength = getMessageHeaderLength();
  140. sendingInProgress = true;
  141. }
  142. size_t writtenLength
  143. = peerConnection->sendMessage(msgHeader+getMessageHeaderLength()-leftDataLength,
  144. leftDataLength);
  145. if(writtenLength == leftDataLength) {
  146. headerSent = true;
  147. leftDataLength = blockLength;
  148. } else {
  149. leftDataLength -= writtenLength;
  150. }
  151. }
  152. if(headerSent) {
  153. sendingInProgress = false;
  154. off_t pieceDataOffset =
  155. (off_t)index*btContext->getPieceLength()+begin+blockLength-leftDataLength;
  156. size_t writtenLength = sendPieceData(pieceDataOffset, leftDataLength);
  157. peer->updateUploadLength(writtenLength);
  158. if(writtenLength < leftDataLength) {
  159. sendingInProgress = true;
  160. }
  161. leftDataLength -= writtenLength;
  162. }
  163. }
  164. size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const {
  165. size_t BUF_SIZE = 256;
  166. unsigned char buf[BUF_SIZE];
  167. div_t res = div(length, BUF_SIZE);
  168. size_t writtenLength = 0;
  169. for(int i = 0; i < res.quot; i++) {
  170. if((size_t)pieceStorage->getDiskAdaptor()->readData(buf, BUF_SIZE, offset+i*BUF_SIZE) < BUF_SIZE) {
  171. throw DlAbortEx(EX_DATA_READ);
  172. }
  173. size_t ws = peerConnection->sendMessage(buf, BUF_SIZE);
  174. writtenLength += ws;
  175. if(ws != BUF_SIZE) {
  176. return writtenLength;
  177. }
  178. }
  179. if(res.rem > 0) {
  180. if(pieceStorage->getDiskAdaptor()->readData(buf, res.rem, offset+res.quot*BUF_SIZE) < res.rem) {
  181. throw DlAbortEx(EX_DATA_READ);
  182. }
  183. size_t ws = peerConnection->sendMessage(buf, res.rem);
  184. writtenLength += ws;
  185. }
  186. return writtenLength;
  187. }
  188. std::string BtPieceMessage::toString() const {
  189. return "piece index="+Util::itos(index)+", begin="+Util::itos(begin)+
  190. ", length="+Util::itos(blockLength);
  191. }
  192. bool BtPieceMessage::checkPieceHash(const PieceHandle& piece) {
  193. off_t offset = (off_t)piece->getIndex()*btContext->getPieceLength();
  194. return MessageDigestHelper::staticSHA1Digest(pieceStorage->getDiskAdaptor(), offset, piece->getLength())
  195. == btContext->getPieceHash(piece->getIndex());
  196. }
  197. void BtPieceMessage::onNewPiece(const PieceHandle& piece) {
  198. logger->info(MSG_GOT_NEW_PIECE, cuid, piece->getIndex());
  199. pieceStorage->completePiece(piece);
  200. pieceStorage->advertisePiece(cuid, piece->getIndex());
  201. }
  202. void BtPieceMessage::onWrongPiece(const PieceHandle& piece) {
  203. logger->info(MSG_GOT_WRONG_PIECE, cuid, piece->getIndex());
  204. erasePieceOnDisk(piece);
  205. piece->clearAllBlock();
  206. requestFactory->removeTargetPiece(piece);
  207. }
  208. void BtPieceMessage::erasePieceOnDisk(const PieceHandle& piece) {
  209. size_t BUFSIZE = 4096;
  210. unsigned char buf[BUFSIZE];
  211. memset(buf, 0, BUFSIZE);
  212. off_t offset = (off_t)piece->getIndex()*btContext->getPieceLength();
  213. div_t res = div(piece->getLength(), BUFSIZE);
  214. for(int i = 0; i < res.quot; i++) {
  215. pieceStorage->getDiskAdaptor()->writeData(buf, BUFSIZE, offset);
  216. offset += BUFSIZE;
  217. }
  218. if(res.rem > 0) {
  219. pieceStorage->getDiskAdaptor()->writeData(buf, res.rem, offset);
  220. }
  221. }
  222. bool BtPieceMessage::BtChokingEventListener::canHandle(const BtEventHandle& event) {
  223. BtChokingEvent* intEvent = dynamic_cast<BtChokingEvent*>(event.get());
  224. return intEvent != 0;
  225. }
  226. void BtPieceMessage::BtChokingEventListener::handleEventInternal(const BtEventHandle& event) {
  227. message->handleChokingEvent(event);
  228. }
  229. void BtPieceMessage::handleChokingEvent(const BtEventHandle& event) {
  230. if(!invalidate &&
  231. !sendingInProgress &&
  232. !peer->isInAmAllowedIndexSet(index)) {
  233. logger->debug(MSG_REJECT_PIECE_CHOKED,
  234. cuid,
  235. index,
  236. begin,
  237. blockLength);
  238. if(peer->isFastExtensionEnabled()) {
  239. BtMessageHandle rej = messageFactory->createRejectMessage(index,
  240. begin,
  241. blockLength);
  242. dispatcher->addMessageToQueue(rej);
  243. }
  244. invalidate = true;
  245. }
  246. }
  247. bool BtPieceMessage::BtCancelSendingPieceEventListener::canHandle(const BtEventHandle& event) {
  248. BtCancelSendingPieceEvent* intEvent = dynamic_cast<BtCancelSendingPieceEvent*>(event.get());
  249. return intEvent != 0;
  250. }
  251. void BtPieceMessage::BtCancelSendingPieceEventListener::handleEventInternal(const BtEventHandle& event) {
  252. message->handleCancelSendingPieceEvent(event);
  253. }
  254. void BtPieceMessage::handleCancelSendingPieceEvent(const BtEventHandle& event) {
  255. BtCancelSendingPieceEvent* intEvent = (BtCancelSendingPieceEvent*)(event.get());
  256. if(!invalidate &&
  257. !sendingInProgress &&
  258. index == intEvent->getIndex() &&
  259. begin == intEvent->getBegin() &&
  260. blockLength == intEvent->getLength()) {
  261. logger->debug(MSG_REJECT_PIECE_CANCEL,
  262. cuid, index, begin, blockLength);
  263. if(peer->isFastExtensionEnabled()) {
  264. BtMessageHandle rej = messageFactory->createRejectMessage(index,
  265. begin,
  266. blockLength);
  267. dispatcher->addMessageToQueue(rej);
  268. }
  269. invalidate = true;
  270. }
  271. }
  272. } // namespace aria2