DownloadCommand.cc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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 "DownloadCommand.h"
  36. #include "Request.h"
  37. #include "RequestGroup.h"
  38. #include "DownloadEngine.h"
  39. #include "PeerStat.h"
  40. #include "TransferEncoding.h"
  41. #include "DlAbortEx.h"
  42. #include "DlRetryEx.h"
  43. #include "SegmentMan.h"
  44. #include "Segment.h"
  45. #include "Logger.h"
  46. #include "ChecksumCheckIntegrityEntry.h"
  47. #include "PieceStorage.h"
  48. #include "CheckIntegrityCommand.h"
  49. #include "DiskAdaptor.h"
  50. #include "CUIDCounter.h"
  51. #include "DownloadContext.h"
  52. #include "Option.h"
  53. #include "Util.h"
  54. #include "Socket.h"
  55. #include "message.h"
  56. #include "prefs.h"
  57. #include "StringFormat.h"
  58. #ifdef ENABLE_MESSAGE_DIGEST
  59. # include "MessageDigestHelper.h"
  60. #endif // ENABLE_MESSAGE_DIGEST
  61. #include <cassert>
  62. namespace aria2 {
  63. DownloadCommand::DownloadCommand(int cuid,
  64. const RequestHandle& req,
  65. RequestGroup* requestGroup,
  66. DownloadEngine* e,
  67. const SocketHandle& s):
  68. AbstractCommand(cuid, req, requestGroup, e, s)
  69. #ifdef ENABLE_MESSAGE_DIGEST
  70. , _pieceHashValidationEnabled(false)
  71. #endif // ENABLE_MESSAGE_DIGEST
  72. {
  73. #ifdef ENABLE_MESSAGE_DIGEST
  74. {
  75. if(e->option->getAsBool(PREF_REALTIME_CHUNK_CHECKSUM)) {
  76. std::string algo = _requestGroup->getDownloadContext()->getPieceHashAlgo();
  77. if(MessageDigestContext::supports(algo)) {
  78. _messageDigestContext.reset(new MessageDigestContext());
  79. _messageDigestContext->trySetAlgo(algo);
  80. _messageDigestContext->digestInit();
  81. _pieceHashValidationEnabled = true;
  82. }
  83. }
  84. }
  85. #endif // ENABLE_MESSAGE_DIGEST
  86. peerStat = _requestGroup->getSegmentMan()->getPeerStat(cuid);
  87. if(peerStat.isNull()) {
  88. peerStat.reset(new PeerStat(cuid));
  89. _requestGroup->getSegmentMan()->registerPeerStat(peerStat);
  90. }
  91. peerStat->downloadStart();
  92. }
  93. DownloadCommand::~DownloadCommand() {
  94. assert(peerStat.get());
  95. peerStat->downloadStop();
  96. }
  97. bool DownloadCommand::executeInternal() {
  98. if(maxDownloadSpeedLimit > 0 &&
  99. maxDownloadSpeedLimit < _requestGroup->getSegmentMan()->calculateDownloadSpeed()) {
  100. e->commands.push_back(this);
  101. disableReadCheckSocket();
  102. return false;
  103. }
  104. setReadCheckSocket(socket);
  105. SegmentHandle segment = _segments.front();
  106. size_t BUFSIZE = 16*1024;
  107. unsigned char buf[BUFSIZE];
  108. size_t bufSize;
  109. if(segment->getLength() > 0 && segment->getLength()-segment->getWrittenLength() < BUFSIZE) {
  110. bufSize = segment->getLength()-segment->getWrittenLength();
  111. } else {
  112. bufSize = BUFSIZE;
  113. }
  114. socket->readData(buf, bufSize);
  115. if(transferDecoder.isNull()) {
  116. _requestGroup->getPieceStorage()->getDiskAdaptor()->writeData(buf, bufSize,
  117. segment->getPositionToWrite());
  118. //logger->debug("bufSize = %d, posToWrite = %lld", bufSize, segment->getPositionToWrite());
  119. #ifdef ENABLE_MESSAGE_DIGEST
  120. if(_pieceHashValidationEnabled) {
  121. segment->updateHash(segment->getWrittenLength(), buf, bufSize);
  122. }
  123. #endif // ENABLE_MESSAGE_DIGEST
  124. segment->updateWrittenLength(bufSize);
  125. //logger->debug("overflow length = %d, next posToWrite = %lld", segment->getOverflowLength(), segment->getPositionToWrite());
  126. //logger->debug("%s", Util::toHex(segment->getPiece()->getBitfield(),
  127. //segment->getPiece()->getBitfieldLength()).c_str());
  128. //segment->writtenLength += bufSize;
  129. peerStat->updateDownloadLength(bufSize);
  130. } else {
  131. size_t infbufSize = 16*1024;
  132. unsigned char infbuf[infbufSize];
  133. transferDecoder->inflate(infbuf, infbufSize, buf, bufSize);
  134. _requestGroup->getPieceStorage()->getDiskAdaptor()->writeData(infbuf, infbufSize,
  135. segment->getPositionToWrite());
  136. #ifdef ENABLE_MESSAGE_DIGEST
  137. if(_pieceHashValidationEnabled) {
  138. segment->updateHash(segment->getWrittenLength(), infbuf, infbufSize);
  139. }
  140. #endif // ENABLE_MESSAGE_DIGEST
  141. segment->updateWrittenLength(infbufSize);
  142. //segment->writtenLength += infbufSize;
  143. peerStat->updateDownloadLength(infbufSize);
  144. }
  145. if(_requestGroup->getTotalLength() != 0 && bufSize == 0) {
  146. throw DlRetryEx(EX_GOT_EOF);
  147. }
  148. if((!transferDecoder.isNull() && transferDecoder->finished())
  149. || (transferDecoder.isNull() && segment->complete())
  150. || bufSize == 0) {
  151. if(!transferDecoder.isNull()) transferDecoder->end();
  152. logger->info(MSG_SEGMENT_DOWNLOAD_COMPLETED, cuid);
  153. #ifdef ENABLE_MESSAGE_DIGEST
  154. {
  155. std::string expectedPieceHash =
  156. _requestGroup->getDownloadContext()->getPieceHash(segment->getIndex());
  157. if(_pieceHashValidationEnabled && !expectedPieceHash.empty()) {
  158. if(segment->isHashCalculated()) {
  159. logger->debug("Hash is available! index=%zu", segment->getIndex());
  160. validatePieceHash(segment, expectedPieceHash, segment->getHashString());
  161. } else {
  162. _messageDigestContext->digestReset();
  163. validatePieceHash(segment, expectedPieceHash,
  164. MessageDigestHelper::digest
  165. (_messageDigestContext.get(),
  166. _requestGroup->getPieceStorage()->getDiskAdaptor(),
  167. segment->getPosition(),
  168. segment->getLength()));
  169. }
  170. } else {
  171. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  172. }
  173. }
  174. #else // !ENABLE_MESSAGE_DIGEST
  175. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  176. #endif // !ENABLE_MESSAGE_DIGEST
  177. checkLowestDownloadSpeed();
  178. // this unit is going to download another segment.
  179. return prepareForNextSegment();
  180. } else {
  181. checkLowestDownloadSpeed();
  182. e->commands.push_back(this);
  183. return false;
  184. }
  185. }
  186. void DownloadCommand::checkLowestDownloadSpeed() const
  187. {
  188. // calculate downloading speed
  189. if(peerStat->getDownloadStartTime().elapsed(startupIdleTime)) {
  190. unsigned int nowSpeed = peerStat->calculateDownloadSpeed();
  191. if(lowestDownloadSpeedLimit > 0 && nowSpeed <= lowestDownloadSpeedLimit) {
  192. throw DlAbortEx(StringFormat(EX_TOO_SLOW_DOWNLOAD_SPEED,
  193. nowSpeed,
  194. lowestDownloadSpeedLimit,
  195. req->getHost().c_str()).str());
  196. }
  197. }
  198. }
  199. bool DownloadCommand::prepareForNextSegment() {
  200. if(_requestGroup->downloadFinished()) {
  201. #ifdef ENABLE_MESSAGE_DIGEST
  202. CheckIntegrityEntryHandle entry(new ChecksumCheckIntegrityEntry(_requestGroup));
  203. if(entry->isValidationReady()) {
  204. entry->initValidator();
  205. CheckIntegrityCommand* command =
  206. new CheckIntegrityCommand(CUIDCounterSingletonHolder::instance()->newID(), _requestGroup, e, entry);
  207. e->commands.push_back(command);
  208. }
  209. #endif // ENABLE_MESSAGE_DIGEST
  210. return true;
  211. } else {
  212. if(_segments.size()) {
  213. SegmentHandle tempSegment = _segments.front();
  214. SegmentHandle nextSegment =
  215. _requestGroup->getSegmentMan()->getSegment(cuid,
  216. tempSegment->getIndex()+1);
  217. if(!nextSegment.isNull() && nextSegment->getWrittenLength() == 0) {
  218. e->commands.push_back(this);
  219. return false;
  220. } else {
  221. return prepareForRetry(0);
  222. }
  223. } else {
  224. return prepareForRetry(0);
  225. }
  226. }
  227. }
  228. #ifdef ENABLE_MESSAGE_DIGEST
  229. void DownloadCommand::validatePieceHash(const SharedHandle<Segment>& segment,
  230. const std::string& expectedPieceHash,
  231. const std::string& actualPieceHash)
  232. {
  233. if(actualPieceHash == expectedPieceHash) {
  234. logger->info(MSG_GOOD_CHUNK_CHECKSUM, actualPieceHash.c_str());
  235. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  236. } else {
  237. logger->info(EX_INVALID_CHUNK_CHECKSUM,
  238. segment->getIndex(),
  239. Util::itos(segment->getPosition(), true).c_str(),
  240. expectedPieceHash.c_str(),
  241. actualPieceHash.c_str());
  242. segment->clear();
  243. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  244. throw DlRetryEx
  245. (StringFormat("Invalid checksum index=%d", segment->getIndex()).str());
  246. }
  247. }
  248. #endif // ENABLE_MESSAGE_DIGEST
  249. void DownloadCommand::setTransferDecoder(const TransferEncodingHandle& transferDecoder)
  250. {
  251. this->transferDecoder = transferDecoder;
  252. }
  253. } // namespace aria2