DownloadCommand.cc 8.2 KB

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