DownloadCommand.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. #include "RequestGroupMan.h"
  59. #ifdef ENABLE_MESSAGE_DIGEST
  60. # include "MessageDigestHelper.h"
  61. #endif // ENABLE_MESSAGE_DIGEST
  62. namespace aria2 {
  63. DownloadCommand::DownloadCommand(int cuid,
  64. const RequestHandle& req,
  65. const SharedHandle<FileEntry>& fileEntry,
  66. RequestGroup* requestGroup,
  67. DownloadEngine* e,
  68. const SocketHandle& s):
  69. AbstractCommand(cuid, req, fileEntry, requestGroup, e, s),
  70. _buf(new unsigned char[BUFSIZE])
  71. #ifdef ENABLE_MESSAGE_DIGEST
  72. , _pieceHashValidationEnabled(false)
  73. #endif // ENABLE_MESSAGE_DIGEST
  74. {
  75. #ifdef ENABLE_MESSAGE_DIGEST
  76. {
  77. if(getOption()->getAsBool(PREF_REALTIME_CHUNK_CHECKSUM)) {
  78. std::string algo = _requestGroup->getDownloadContext()->getPieceHashAlgo();
  79. if(MessageDigestContext::supports(algo)) {
  80. _messageDigestContext.reset(new MessageDigestContext());
  81. _messageDigestContext->trySetAlgo(algo);
  82. _messageDigestContext->digestInit();
  83. _pieceHashValidationEnabled = true;
  84. }
  85. }
  86. }
  87. #endif // ENABLE_MESSAGE_DIGEST
  88. peerStat = req->initPeerStat();
  89. peerStat->downloadStart();
  90. _requestGroup->getSegmentMan()->registerPeerStat(peerStat);
  91. }
  92. DownloadCommand::~DownloadCommand() {
  93. peerStat->downloadStop();
  94. _requestGroup->getSegmentMan()->updateFastestPeerStat(peerStat);
  95. }
  96. bool DownloadCommand::executeInternal() {
  97. if(e->_requestGroupMan->doesOverallDownloadSpeedExceed() ||
  98. _requestGroup->doesDownloadSpeedExceed()) {
  99. e->commands.push_back(this);
  100. disableReadCheckSocket();
  101. return false;
  102. }
  103. setReadCheckSocket(socket);
  104. SegmentHandle segment = _segments.front();
  105. size_t bufSize;
  106. if(segment->getLength() > 0) {
  107. if(segment->getPosition()+segment->getLength() <= static_cast<uint64_t>(_fileEntry->getLastOffset())) {
  108. bufSize = std::min(segment->getLength()-segment->getWrittenLength(),
  109. BUFSIZE);
  110. } else {
  111. bufSize = std::min(static_cast<size_t>(_fileEntry->getLastOffset()-segment->getPositionToWrite()), BUFSIZE);
  112. }
  113. } else {
  114. bufSize = BUFSIZE;
  115. }
  116. socket->readData(_buf, bufSize);
  117. const SharedHandle<DiskAdaptor>& diskAdaptor =
  118. _requestGroup->getPieceStorage()->getDiskAdaptor();
  119. const unsigned char* bufFinal;
  120. size_t bufSizeFinal;
  121. std::string decoded;
  122. if(_transferEncodingDecoder.isNull()) {
  123. bufFinal = _buf;
  124. bufSizeFinal = bufSize;
  125. } else {
  126. decoded = _transferEncodingDecoder->decode(_buf, bufSize);
  127. bufFinal = reinterpret_cast<const unsigned char*>(decoded.c_str());
  128. bufSizeFinal = decoded.size();
  129. }
  130. if(_contentEncodingDecoder.isNull()) {
  131. diskAdaptor->writeData(bufFinal, bufSizeFinal,
  132. segment->getPositionToWrite());
  133. } else {
  134. std::string out = _contentEncodingDecoder->decode(bufFinal, bufSizeFinal);
  135. diskAdaptor->writeData(reinterpret_cast<const unsigned char*>(out.data()),
  136. out.size(),
  137. segment->getPositionToWrite());
  138. bufSizeFinal = out.size();
  139. }
  140. #ifdef ENABLE_MESSAGE_DIGEST
  141. if(_pieceHashValidationEnabled) {
  142. segment->updateHash(segment->getWrittenLength(), bufFinal, bufSizeFinal);
  143. }
  144. #endif // ENABLE_MESSAGE_DIGEST
  145. if(bufSizeFinal > 0) {
  146. segment->updateWrittenLength(bufSizeFinal);
  147. }
  148. peerStat->updateDownloadLength(bufSize);
  149. _requestGroup->getSegmentMan()->updateDownloadSpeedFor(peerStat);
  150. bool segmentComplete = false;
  151. // Note that GrowSegment::complete() always returns false.
  152. if(_transferEncodingDecoder.isNull() && _contentEncodingDecoder.isNull()) {
  153. if(segment->complete() ||
  154. segment->getPositionToWrite() == _fileEntry->getLastOffset()) {
  155. segmentComplete = true;
  156. } else if(segment->getLength() == 0 && bufSize == 0 &&
  157. !socket->wantRead() && !socket->wantWrite()) {
  158. segmentComplete = true;
  159. }
  160. } else if(!_transferEncodingDecoder.isNull() &&
  161. (segment->complete() || segment->getPositionToWrite() == _fileEntry->getLastOffset())) {
  162. segmentComplete = true;
  163. } else if((_transferEncodingDecoder.isNull() ||
  164. _transferEncodingDecoder->finished()) &&
  165. (_contentEncodingDecoder.isNull() ||
  166. _contentEncodingDecoder->finished())) {
  167. segmentComplete = true;
  168. }
  169. if(!segmentComplete && bufSize == 0 &&
  170. !socket->wantRead() && !socket->wantWrite()) {
  171. throw DL_RETRY_EX(EX_GOT_EOF);
  172. }
  173. if(segmentComplete) {
  174. if(segment->complete() || segment->getLength() == 0) {
  175. // If segment->getLength() == 0, the server doesn't provide
  176. // content length, but the client detected that download
  177. // completed.
  178. logger->info(MSG_SEGMENT_DOWNLOAD_COMPLETED, cuid);
  179. #ifdef ENABLE_MESSAGE_DIGEST
  180. {
  181. std::string expectedPieceHash =
  182. _requestGroup->getDownloadContext()->getPieceHash(segment->getIndex());
  183. if(_pieceHashValidationEnabled && !expectedPieceHash.empty()) {
  184. if(segment->isHashCalculated()) {
  185. logger->debug("Hash is available! index=%lu",
  186. static_cast<unsigned long>(segment->getIndex()));
  187. validatePieceHash(segment, expectedPieceHash, segment->getHashString());
  188. } else {
  189. _messageDigestContext->digestReset();
  190. validatePieceHash(segment, expectedPieceHash,
  191. MessageDigestHelper::digest
  192. (_messageDigestContext.get(),
  193. _requestGroup->getPieceStorage()->getDiskAdaptor(),
  194. segment->getPosition(),
  195. segment->getLength()));
  196. }
  197. } else {
  198. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  199. }
  200. }
  201. #else // !ENABLE_MESSAGE_DIGEST
  202. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  203. #endif // !ENABLE_MESSAGE_DIGEST
  204. } else {
  205. // If segment is not cacnel here, in the next pipelining
  206. // request, aria2 requests bad range
  207. // [FileEntry->getLastOffset(), FileEntry->getLastOffset())
  208. _requestGroup->getSegmentMan()->cancelSegment(cuid, segment);
  209. }
  210. checkLowestDownloadSpeed();
  211. // this unit is going to download another segment.
  212. return prepareForNextSegment();
  213. } else {
  214. checkLowestDownloadSpeed();
  215. setWriteCheckSocketIf(socket, socket->wantWrite());
  216. e->commands.push_back(this);
  217. return false;
  218. }
  219. }
  220. void DownloadCommand::checkLowestDownloadSpeed() const
  221. {
  222. // calculate downloading speed
  223. if(peerStat->getDownloadStartTime().elapsed(startupIdleTime)) {
  224. unsigned int nowSpeed = peerStat->calculateDownloadSpeed();
  225. if(lowestDownloadSpeedLimit > 0 && nowSpeed <= lowestDownloadSpeedLimit) {
  226. throw DL_ABORT_EX2(StringFormat(EX_TOO_SLOW_DOWNLOAD_SPEED,
  227. nowSpeed,
  228. lowestDownloadSpeedLimit,
  229. req->getHost().c_str()).str(),
  230. downloadresultcode::TOO_SLOW_DOWNLOAD_SPEED);
  231. }
  232. }
  233. }
  234. bool DownloadCommand::prepareForNextSegment() {
  235. if(_requestGroup->downloadFinished()) {
  236. // If this is a single file download, and file size becomes known
  237. // just after downloading, set total length to FileEntry object
  238. // here.
  239. if(_requestGroup->getDownloadContext()->getFileEntries().size() == 1) {
  240. const SharedHandle<FileEntry>& fileEntry =
  241. _requestGroup->getDownloadContext()->getFirstFileEntry();
  242. if(fileEntry->getLength() == 0) {
  243. fileEntry->setLength
  244. (_requestGroup->getPieceStorage()->getCompletedLength());
  245. }
  246. }
  247. #ifdef ENABLE_MESSAGE_DIGEST
  248. CheckIntegrityEntryHandle entry(new ChecksumCheckIntegrityEntry(_requestGroup));
  249. if(entry->isValidationReady()) {
  250. entry->initValidator();
  251. // TODO do we need cuttrailinggarbage here?
  252. e->_checkIntegrityMan->pushEntry(entry);
  253. }
  254. e->setNoWait(true);
  255. e->setRefreshInterval(0);
  256. #endif // ENABLE_MESSAGE_DIGEST
  257. return true;
  258. } else {
  259. // The number of segments should be 1 in order to pass through the next
  260. // segment.
  261. if(_segments.size() == 1) {
  262. SegmentHandle tempSegment = _segments.front();
  263. if(!tempSegment->complete()) {
  264. return prepareForRetry(0);
  265. }
  266. // TODO1.5 get segment for the same file only
  267. SegmentHandle nextSegment =
  268. _requestGroup->getSegmentMan()->getSegment(cuid,
  269. tempSegment->getIndex()+1);
  270. if(!nextSegment.isNull() && nextSegment->getWrittenLength() == 0) {
  271. e->commands.push_back(this);
  272. return false;
  273. } else {
  274. return prepareForRetry(0);
  275. }
  276. } else {
  277. return prepareForRetry(0);
  278. }
  279. }
  280. }
  281. #ifdef ENABLE_MESSAGE_DIGEST
  282. void DownloadCommand::validatePieceHash(const SharedHandle<Segment>& segment,
  283. const std::string& expectedPieceHash,
  284. const std::string& actualPieceHash)
  285. {
  286. if(actualPieceHash == expectedPieceHash) {
  287. logger->info(MSG_GOOD_CHUNK_CHECKSUM, actualPieceHash.c_str());
  288. _requestGroup->getSegmentMan()->completeSegment(cuid, segment);
  289. } else {
  290. logger->info(EX_INVALID_CHUNK_CHECKSUM,
  291. segment->getIndex(),
  292. Util::itos(segment->getPosition(), true).c_str(),
  293. expectedPieceHash.c_str(),
  294. actualPieceHash.c_str());
  295. segment->clear();
  296. _requestGroup->getSegmentMan()->cancelSegment(cuid);
  297. throw DL_RETRY_EX
  298. (StringFormat("Invalid checksum index=%d", segment->getIndex()).str());
  299. }
  300. }
  301. #endif // ENABLE_MESSAGE_DIGEST
  302. void DownloadCommand::setTransferEncodingDecoder
  303. (const SharedHandle<Decoder>& decoder)
  304. {
  305. this->_transferEncodingDecoder = decoder;
  306. }
  307. void DownloadCommand::setContentEncodingDecoder
  308. (const SharedHandle<Decoder>& decoder)
  309. {
  310. _contentEncodingDecoder = decoder;
  311. }
  312. } // namespace aria2