DownloadCommand.cc 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 <cassert>
  37. #include "Request.h"
  38. #include "RequestGroup.h"
  39. #include "DownloadEngine.h"
  40. #include "PeerStat.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 "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. 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. #ifdef ENABLE_MESSAGE_DIGEST
  69. , _pieceHashValidationEnabled(false)
  70. #endif // ENABLE_MESSAGE_DIGEST
  71. {
  72. #ifdef ENABLE_MESSAGE_DIGEST
  73. {
  74. if(e->option->getAsBool(PREF_REALTIME_CHUNK_CHECKSUM)) {
  75. std::string algo = _requestGroup->getDownloadContext()->getPieceHashAlgo();
  76. if(MessageDigestContext::supports(algo)) {
  77. _messageDigestContext.reset(new MessageDigestContext());
  78. _messageDigestContext->trySetAlgo(algo);
  79. _messageDigestContext->digestInit();
  80. _pieceHashValidationEnabled = true;
  81. }
  82. }
  83. }
  84. #endif // ENABLE_MESSAGE_DIGEST
  85. peerStat = _requestGroup->getSegmentMan()->getPeerStat(cuid);
  86. if(peerStat.isNull()) {
  87. peerStat.reset(new PeerStat(cuid, req->getHost(), req->getProtocol()));
  88. _requestGroup->getSegmentMan()->registerPeerStat(peerStat);
  89. }
  90. peerStat->downloadStart();
  91. }
  92. DownloadCommand::~DownloadCommand() {
  93. assert(peerStat.get());
  94. peerStat->downloadStop();
  95. }
  96. bool DownloadCommand::executeInternal() {
  97. if(maxDownloadSpeedLimit > 0 &&
  98. maxDownloadSpeedLimit <
  99. _requestGroup->calculateStat().getDownloadSpeed()) {
  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. !socket->wantRead() && !socket->wantWrite()) {
  147. throw DlRetryEx(EX_GOT_EOF);
  148. }
  149. bool segmentComplete = false;
  150. if(_transferEncodingDecoder.isNull() && _contentEncodingDecoder.isNull()) {
  151. if(segment->complete()) {
  152. segmentComplete = true;
  153. } else if(segment->getLength() == 0 && bufSize == 0 &&
  154. !socket->wantRead() && !socket->wantWrite()) {
  155. segmentComplete = true;
  156. }
  157. } else if(!_transferEncodingDecoder.isNull() &&
  158. !_contentEncodingDecoder.isNull()) {
  159. if(_transferEncodingDecoder->finished() &&
  160. _contentEncodingDecoder->finished()) {
  161. segmentComplete = true;
  162. }
  163. } else if(!_transferEncodingDecoder.isNull() &&
  164. _contentEncodingDecoder.isNull()) {
  165. if(_transferEncodingDecoder->finished()) {
  166. segmentComplete = true;
  167. }
  168. } else if(_transferEncodingDecoder.isNull() &&
  169. !_contentEncodingDecoder.isNull()) {
  170. if(_contentEncodingDecoder->finished()) {
  171. segmentComplete = true;
  172. }
  173. }
  174. if(segmentComplete) {
  175. logger->info(MSG_SEGMENT_DOWNLOAD_COMPLETED, cuid);
  176. #ifdef ENABLE_MESSAGE_DIGEST
  177. {
  178. std::string expectedPieceHash =
  179. _requestGroup->getDownloadContext()->getPieceHash(segment->getIndex());
  180. if(_pieceHashValidationEnabled && !expectedPieceHash.empty()) {
  181. if(segment->isHashCalculated()) {
  182. logger->debug("Hash is available! index=%lu",
  183. static_cast<unsigned long>(segment->getIndex()));
  184. validatePieceHash(segment, expectedPieceHash, segment->getHashString());
  185. } else {
  186. _messageDigestContext->digestReset();
  187. validatePieceHash(segment, expectedPieceHash,
  188. MessageDigestHelper::digest
  189. (_messageDigestContext.get(),
  190. _requestGroup->getPieceStorage()->getDiskAdaptor(),
  191. segment->getPosition(),
  192. segment->getLength()));
  193. }
  194. } else {
  195. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  196. }
  197. }
  198. #else // !ENABLE_MESSAGE_DIGEST
  199. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  200. #endif // !ENABLE_MESSAGE_DIGEST
  201. checkLowestDownloadSpeed();
  202. // this unit is going to download another segment.
  203. return prepareForNextSegment();
  204. } else {
  205. checkLowestDownloadSpeed();
  206. setWriteCheckSocketIf(socket, socket->wantWrite());
  207. e->commands.push_back(this);
  208. return false;
  209. }
  210. }
  211. void DownloadCommand::checkLowestDownloadSpeed() const
  212. {
  213. // calculate downloading speed
  214. if(peerStat->getDownloadStartTime().elapsed(startupIdleTime)) {
  215. unsigned int nowSpeed = peerStat->calculateDownloadSpeed();
  216. if(lowestDownloadSpeedLimit > 0 && nowSpeed <= lowestDownloadSpeedLimit) {
  217. throw DlAbortEx(StringFormat(EX_TOO_SLOW_DOWNLOAD_SPEED,
  218. nowSpeed,
  219. lowestDownloadSpeedLimit,
  220. req->getHost().c_str()).str(), DownloadResult::TOO_SLOW_DOWNLOAD_SPEED);
  221. }
  222. }
  223. }
  224. bool DownloadCommand::prepareForNextSegment() {
  225. if(_requestGroup->downloadFinished()) {
  226. #ifdef ENABLE_MESSAGE_DIGEST
  227. CheckIntegrityEntryHandle entry(new ChecksumCheckIntegrityEntry(_requestGroup));
  228. if(entry->isValidationReady()) {
  229. entry->initValidator();
  230. CheckIntegrityCommand* command =
  231. new CheckIntegrityCommand(e->newCUID(), _requestGroup, e, entry);
  232. e->commands.push_back(command);
  233. }
  234. e->setNoWait(true);
  235. e->setRefreshInterval(0);
  236. #endif // ENABLE_MESSAGE_DIGEST
  237. return true;
  238. } else {
  239. // The number of segments should be 1 in order to pass through the next
  240. // segment.
  241. if(_segments.size() == 1) {
  242. SegmentHandle tempSegment = _segments.front();
  243. SegmentHandle nextSegment =
  244. _requestGroup->getSegmentMan()->getSegment(cuid,
  245. tempSegment->getIndex()+1);
  246. if(!nextSegment.isNull() && nextSegment->getWrittenLength() == 0) {
  247. e->commands.push_back(this);
  248. return false;
  249. } else {
  250. return prepareForRetry(0);
  251. }
  252. } else {
  253. return prepareForRetry(0);
  254. }
  255. }
  256. }
  257. #ifdef ENABLE_MESSAGE_DIGEST
  258. void DownloadCommand::validatePieceHash(const SharedHandle<Segment>& segment,
  259. const std::string& expectedPieceHash,
  260. const std::string& actualPieceHash)
  261. {
  262. if(actualPieceHash == expectedPieceHash) {
  263. logger->info(MSG_GOOD_CHUNK_CHECKSUM, actualPieceHash.c_str());
  264. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  265. } else {
  266. logger->info(EX_INVALID_CHUNK_CHECKSUM,
  267. segment->getIndex(),
  268. Util::itos(segment->getPosition(), true).c_str(),
  269. expectedPieceHash.c_str(),
  270. actualPieceHash.c_str());
  271. segment->clear();
  272. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  273. throw DlRetryEx
  274. (StringFormat("Invalid checksum index=%d", segment->getIndex()).str());
  275. }
  276. }
  277. #endif // ENABLE_MESSAGE_DIGEST
  278. void DownloadCommand::setTransferEncodingDecoder
  279. (const SharedHandle<Decoder>& decoder)
  280. {
  281. this->_transferEncodingDecoder = decoder;
  282. }
  283. void DownloadCommand::setContentEncodingDecoder
  284. (const SharedHandle<Decoder>& decoder)
  285. {
  286. _contentEncodingDecoder = decoder;
  287. }
  288. } // namespace aria2