DownloadCommand.cc 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 "DlAbortEx.h"
  41. #include "DlRetryEx.h"
  42. #include "SegmentMan.h"
  43. #include "Segment.h"
  44. #include "Logger.h"
  45. #include "ChecksumCheckIntegrityEntry.h"
  46. #include "PieceStorage.h"
  47. #include "CheckIntegrityCommand.h"
  48. #include "DiskAdaptor.h"
  49. #include "CUIDCounter.h"
  50. #include "DownloadContext.h"
  51. #include "Option.h"
  52. #include "Util.h"
  53. #include "Socket.h"
  54. #include "message.h"
  55. #include "prefs.h"
  56. #include "StringFormat.h"
  57. #include "Decoder.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, req->getHost(), req->getProtocol()));
  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. const SharedHandle<DiskAdaptor>& diskAdaptor =
  116. _requestGroup->getPieceStorage()->getDiskAdaptor();
  117. const unsigned char* bufFinal;
  118. size_t bufSizeFinal;
  119. std::string decoded;
  120. if(_transferEncodingDecoder.isNull()) {
  121. bufFinal = buf;
  122. bufSizeFinal = bufSize;
  123. } else {
  124. decoded = _transferEncodingDecoder->decode(buf, bufSize);
  125. bufFinal = reinterpret_cast<const unsigned char*>(decoded.c_str());
  126. bufSizeFinal = decoded.size();
  127. }
  128. if(_contentEncodingDecoder.isNull()) {
  129. diskAdaptor->writeData(bufFinal, bufSizeFinal,
  130. segment->getPositionToWrite());
  131. } else {
  132. std::string out = _contentEncodingDecoder->decode(bufFinal, bufSizeFinal);
  133. diskAdaptor->writeData(reinterpret_cast<const unsigned char*>(out.data()),
  134. out.size(),
  135. segment->getPositionToWrite());
  136. bufSizeFinal = out.size();
  137. }
  138. #ifdef ENABLE_MESSAGE_DIGEST
  139. if(_pieceHashValidationEnabled) {
  140. segment->updateHash(segment->getWrittenLength(), bufFinal, bufSizeFinal);
  141. }
  142. #endif // ENABLE_MESSAGE_DIGEST
  143. segment->updateWrittenLength(bufSizeFinal);
  144. peerStat->updateDownloadLength(bufSize);
  145. if(_requestGroup->getTotalLength() != 0 && bufSize == 0) {
  146. throw DlRetryEx(EX_GOT_EOF);
  147. }
  148. if((!_transferEncodingDecoder.isNull() &&
  149. _transferEncodingDecoder->finished())
  150. || (_transferEncodingDecoder.isNull() && segment->complete())
  151. || (!_contentEncodingDecoder.isNull() &&
  152. _contentEncodingDecoder->finished())
  153. || bufSize == 0) {
  154. logger->info(MSG_SEGMENT_DOWNLOAD_COMPLETED, cuid);
  155. if(!_contentEncodingDecoder.isNull() &&
  156. !_contentEncodingDecoder->finished()) {
  157. logger->warn("CUID#%d - Transfer was completed, but inflate operation"
  158. " have not finished. Maybe the file is broken in the server"
  159. " side.", cuid);
  160. }
  161. #ifdef ENABLE_MESSAGE_DIGEST
  162. {
  163. std::string expectedPieceHash =
  164. _requestGroup->getDownloadContext()->getPieceHash(segment->getIndex());
  165. if(_pieceHashValidationEnabled && !expectedPieceHash.empty()) {
  166. if(segment->isHashCalculated()) {
  167. logger->debug("Hash is available! index=%zu", segment->getIndex());
  168. validatePieceHash(segment, expectedPieceHash, segment->getHashString());
  169. } else {
  170. _messageDigestContext->digestReset();
  171. validatePieceHash(segment, expectedPieceHash,
  172. MessageDigestHelper::digest
  173. (_messageDigestContext.get(),
  174. _requestGroup->getPieceStorage()->getDiskAdaptor(),
  175. segment->getPosition(),
  176. segment->getLength()));
  177. }
  178. } else {
  179. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  180. }
  181. }
  182. #else // !ENABLE_MESSAGE_DIGEST
  183. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  184. #endif // !ENABLE_MESSAGE_DIGEST
  185. checkLowestDownloadSpeed();
  186. // this unit is going to download another segment.
  187. return prepareForNextSegment();
  188. } else {
  189. checkLowestDownloadSpeed();
  190. e->commands.push_back(this);
  191. return false;
  192. }
  193. }
  194. void DownloadCommand::checkLowestDownloadSpeed() const
  195. {
  196. // calculate downloading speed
  197. if(peerStat->getDownloadStartTime().elapsed(startupIdleTime)) {
  198. unsigned int nowSpeed = peerStat->calculateDownloadSpeed();
  199. if(lowestDownloadSpeedLimit > 0 && nowSpeed <= lowestDownloadSpeedLimit) {
  200. throw DlAbortEx(StringFormat(EX_TOO_SLOW_DOWNLOAD_SPEED,
  201. nowSpeed,
  202. lowestDownloadSpeedLimit,
  203. req->getHost().c_str()).str());
  204. }
  205. }
  206. }
  207. bool DownloadCommand::prepareForNextSegment() {
  208. if(_requestGroup->downloadFinished()) {
  209. #ifdef ENABLE_MESSAGE_DIGEST
  210. CheckIntegrityEntryHandle entry(new ChecksumCheckIntegrityEntry(_requestGroup));
  211. if(entry->isValidationReady()) {
  212. entry->initValidator();
  213. CheckIntegrityCommand* command =
  214. new CheckIntegrityCommand(CUIDCounterSingletonHolder::instance()->newID(), _requestGroup, e, entry);
  215. e->commands.push_back(command);
  216. }
  217. #endif // ENABLE_MESSAGE_DIGEST
  218. return true;
  219. } else {
  220. if(_segments.size()) {
  221. SegmentHandle tempSegment = _segments.front();
  222. SegmentHandle nextSegment =
  223. _requestGroup->getSegmentMan()->getSegment(cuid,
  224. tempSegment->getIndex()+1);
  225. if(!nextSegment.isNull() && nextSegment->getWrittenLength() == 0) {
  226. e->commands.push_back(this);
  227. return false;
  228. } else {
  229. return prepareForRetry(0);
  230. }
  231. } else {
  232. return prepareForRetry(0);
  233. }
  234. }
  235. }
  236. #ifdef ENABLE_MESSAGE_DIGEST
  237. void DownloadCommand::validatePieceHash(const SharedHandle<Segment>& segment,
  238. const std::string& expectedPieceHash,
  239. const std::string& actualPieceHash)
  240. {
  241. if(actualPieceHash == expectedPieceHash) {
  242. logger->info(MSG_GOOD_CHUNK_CHECKSUM, actualPieceHash.c_str());
  243. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  244. } else {
  245. logger->info(EX_INVALID_CHUNK_CHECKSUM,
  246. segment->getIndex(),
  247. Util::itos(segment->getPosition(), true).c_str(),
  248. expectedPieceHash.c_str(),
  249. actualPieceHash.c_str());
  250. segment->clear();
  251. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  252. throw DlRetryEx
  253. (StringFormat("Invalid checksum index=%d", segment->getIndex()).str());
  254. }
  255. }
  256. #endif // ENABLE_MESSAGE_DIGEST
  257. void DownloadCommand::setTransferEncodingDecoder
  258. (const SharedHandle<Decoder>& decoder)
  259. {
  260. this->_transferEncodingDecoder = decoder;
  261. }
  262. void DownloadCommand::setContentEncodingDecoder
  263. (const SharedHandle<Decoder>& decoder)
  264. {
  265. _contentEncodingDecoder = decoder;
  266. }
  267. } // namespace aria2