DownloadCommand.cc 12 KB

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