DownloadCommand.cc 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. {
  70. #ifdef ENABLE_MESSAGE_DIGEST
  71. {
  72. std::string algo = _requestGroup->getDownloadContext()->getPieceHashAlgo();
  73. if(MessageDigestContext::supports(algo)) {
  74. _messageDigestContext.reset(new MessageDigestContext());
  75. _messageDigestContext->trySetAlgo(algo);
  76. _messageDigestContext->digestInit();
  77. }
  78. }
  79. #endif // ENABLE_MESSAGE_DIGEST
  80. peerStat = _requestGroup->getSegmentMan()->getPeerStat(cuid);
  81. if(peerStat.isNull()) {
  82. peerStat.reset(new PeerStat(cuid));
  83. _requestGroup->getSegmentMan()->registerPeerStat(peerStat);
  84. }
  85. peerStat->downloadStart();
  86. }
  87. DownloadCommand::~DownloadCommand() {
  88. assert(peerStat.get());
  89. peerStat->downloadStop();
  90. }
  91. bool DownloadCommand::executeInternal() {
  92. if(maxDownloadSpeedLimit > 0 &&
  93. maxDownloadSpeedLimit < _requestGroup->getSegmentMan()->calculateDownloadSpeed()) {
  94. e->commands.push_back(this);
  95. disableReadCheckSocket();
  96. return false;
  97. }
  98. setReadCheckSocket(socket);
  99. SegmentHandle segment = _segments.front();
  100. size_t BUFSIZE = 16*1024;
  101. unsigned char buf[BUFSIZE];
  102. size_t bufSize;
  103. if(segment->getLength() > 0 && segment->getLength()-segment->getWrittenLength() < BUFSIZE) {
  104. bufSize = segment->getLength()-segment->getWrittenLength();
  105. } else {
  106. bufSize = BUFSIZE;
  107. }
  108. socket->readData(buf, bufSize);
  109. if(transferDecoder.isNull()) {
  110. _requestGroup->getPieceStorage()->getDiskAdaptor()->writeData(buf, bufSize,
  111. segment->getPositionToWrite());
  112. //logger->debug("bufSize = %d, posToWrite = %lld", bufSize, segment->getPositionToWrite());
  113. segment->updateWrittenLength(bufSize);
  114. //logger->debug("overflow length = %d, next posToWrite = %lld", segment->getOverflowLength(), segment->getPositionToWrite());
  115. //logger->debug("%s", Util::toHex(segment->getPiece()->getBitfield(),
  116. //segment->getPiece()->getBitfieldLength()).c_str());
  117. //segment->writtenLength += bufSize;
  118. peerStat->updateDownloadLength(bufSize);
  119. } else {
  120. size_t infbufSize = 16*1024;
  121. unsigned char infbuf[infbufSize];
  122. transferDecoder->inflate(infbuf, infbufSize, buf, bufSize);
  123. _requestGroup->getPieceStorage()->getDiskAdaptor()->writeData(infbuf, infbufSize,
  124. segment->getPositionToWrite());
  125. segment->updateWrittenLength(infbufSize);
  126. //segment->writtenLength += infbufSize;
  127. peerStat->updateDownloadLength(infbufSize);
  128. }
  129. if(_requestGroup->getTotalLength() != 0 && bufSize == 0) {
  130. throw DlRetryEx(EX_GOT_EOF);
  131. }
  132. if((!transferDecoder.isNull() && transferDecoder->finished())
  133. || (transferDecoder.isNull() && segment->complete())
  134. || bufSize == 0) {
  135. if(!transferDecoder.isNull()) transferDecoder->end();
  136. logger->info(MSG_SEGMENT_DOWNLOAD_COMPLETED, cuid);
  137. validatePieceHash(segment);
  138. checkLowestDownloadSpeed();
  139. // this unit is going to download another segment.
  140. return prepareForNextSegment();
  141. } else {
  142. checkLowestDownloadSpeed();
  143. e->commands.push_back(this);
  144. return false;
  145. }
  146. }
  147. void DownloadCommand::checkLowestDownloadSpeed() const
  148. {
  149. // calculate downloading speed
  150. if(peerStat->getDownloadStartTime().elapsed(startupIdleTime)) {
  151. unsigned int nowSpeed = peerStat->calculateDownloadSpeed();
  152. if(lowestDownloadSpeedLimit > 0 && nowSpeed <= lowestDownloadSpeedLimit) {
  153. throw DlAbortEx(StringFormat(EX_TOO_SLOW_DOWNLOAD_SPEED,
  154. nowSpeed,
  155. lowestDownloadSpeedLimit,
  156. req->getHost().c_str()).str());
  157. }
  158. }
  159. }
  160. bool DownloadCommand::prepareForNextSegment() {
  161. if(_requestGroup->downloadFinished()) {
  162. #ifdef ENABLE_MESSAGE_DIGEST
  163. CheckIntegrityEntryHandle entry(new ChecksumCheckIntegrityEntry(_requestGroup));
  164. if(entry->isValidationReady()) {
  165. entry->initValidator();
  166. CheckIntegrityCommand* command =
  167. new CheckIntegrityCommand(CUIDCounterSingletonHolder::instance()->newID(), _requestGroup, e, entry);
  168. e->commands.push_back(command);
  169. }
  170. #endif // ENABLE_MESSAGE_DIGEST
  171. return true;
  172. } else {
  173. if(_segments.size()) {
  174. SegmentHandle tempSegment = _segments.front();
  175. SegmentHandle nextSegment =
  176. _requestGroup->getSegmentMan()->getSegment(cuid,
  177. tempSegment->getIndex()+1);
  178. if(!nextSegment.isNull() && nextSegment->getWrittenLength() == 0) {
  179. e->commands.push_back(this);
  180. return false;
  181. } else {
  182. return prepareForRetry(0);
  183. }
  184. } else {
  185. return prepareForRetry(0);
  186. }
  187. }
  188. }
  189. void DownloadCommand::validatePieceHash(const SegmentHandle& segment)
  190. {
  191. #ifdef ENABLE_MESSAGE_DIGEST
  192. std::string expectedPieceHash =
  193. _requestGroup->getDownloadContext()->getPieceHash(segment->getIndex());
  194. if(!_messageDigestContext.isNull() &&
  195. e->option->get(PREF_REALTIME_CHUNK_CHECKSUM) == V_TRUE &&
  196. !expectedPieceHash.empty()) {
  197. _messageDigestContext->digestReset();
  198. std::string actualPieceHash =
  199. MessageDigestHelper::digest(_messageDigestContext.get(),
  200. _requestGroup->getPieceStorage()->getDiskAdaptor(),
  201. segment->getPosition(),
  202. segment->getLength());
  203. if(actualPieceHash == expectedPieceHash) {
  204. logger->info(MSG_GOOD_CHUNK_CHECKSUM, actualPieceHash.c_str());
  205. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  206. } else {
  207. logger->info(EX_INVALID_CHUNK_CHECKSUM,
  208. segment->getIndex(),
  209. Util::itos(segment->getPosition(), true).c_str(),
  210. expectedPieceHash.c_str(),
  211. actualPieceHash.c_str());
  212. segment->clear();
  213. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  214. throw DlRetryEx
  215. (StringFormat("Invalid checksum index=%d", segment->getIndex()).str());
  216. }
  217. } else
  218. #endif // ENABLE_MESSAGE_DIGEST
  219. {
  220. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  221. }
  222. }
  223. void DownloadCommand::setTransferDecoder(const TransferEncodingHandle& transferDecoder)
  224. {
  225. this->transferDecoder = transferDecoder;
  226. }
  227. } // namespace aria2