DownloadCommand.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 "LogFactory.h"
  47. #include "ChecksumCheckIntegrityEntry.h"
  48. #include "PieceStorage.h"
  49. #include "CheckIntegrityCommand.h"
  50. #include "DiskAdaptor.h"
  51. #include "DownloadContext.h"
  52. #include "Option.h"
  53. #include "util.h"
  54. #include "SocketCore.h"
  55. #include "message.h"
  56. #include "prefs.h"
  57. #include "fmt.h"
  58. #include "RequestGroupMan.h"
  59. #include "wallclock.h"
  60. #include "SinkStreamFilter.h"
  61. #include "FileEntry.h"
  62. #include "SocketRecvBuffer.h"
  63. #include "Piece.h"
  64. #include "WrDiskCacheEntry.h"
  65. #include "DownloadFailureException.h"
  66. #ifdef ENABLE_MESSAGE_DIGEST
  67. # include "MessageDigest.h"
  68. # include "message_digest_helper.h"
  69. #endif // ENABLE_MESSAGE_DIGEST
  70. #ifdef ENABLE_BITTORRENT
  71. # include "bittorrent_helper.h"
  72. #endif // ENABLE_BITTORRENT
  73. namespace aria2 {
  74. namespace {
  75. const size_t BUFSIZE = 16*1024;
  76. } // namespace
  77. DownloadCommand::DownloadCommand
  78. (cuid_t cuid,
  79. const std::shared_ptr<Request>& req,
  80. const std::shared_ptr<FileEntry>& fileEntry,
  81. RequestGroup* requestGroup,
  82. DownloadEngine* e,
  83. const std::shared_ptr<SocketCore>& s,
  84. const std::shared_ptr<SocketRecvBuffer>& socketRecvBuffer)
  85. : AbstractCommand(cuid, req, fileEntry, requestGroup, e, s, socketRecvBuffer),
  86. startupIdleTime_(10),
  87. lowestDownloadSpeedLimit_(0),
  88. pieceHashValidationEnabled_(false)
  89. {
  90. #ifdef ENABLE_MESSAGE_DIGEST
  91. {
  92. if(getOption()->getAsBool(PREF_REALTIME_CHUNK_CHECKSUM)) {
  93. const std::string& algo = getDownloadContext()->getPieceHashType();
  94. if(MessageDigest::supports(algo)) {
  95. messageDigest_ = MessageDigest::create(algo);
  96. pieceHashValidationEnabled_ = true;
  97. }
  98. }
  99. }
  100. #endif // ENABLE_MESSAGE_DIGEST
  101. peerStat_ = req->initPeerStat();
  102. peerStat_->downloadStart();
  103. getSegmentMan()->registerPeerStat(peerStat_);
  104. streamFilter_ = make_unique<SinkStreamFilter>
  105. (getPieceStorage()->getWrDiskCache(), pieceHashValidationEnabled_);
  106. streamFilter_->init();
  107. sinkFilterOnly_ = true;
  108. checkSocketRecvBuffer();
  109. }
  110. DownloadCommand::~DownloadCommand() {
  111. peerStat_->downloadStop();
  112. getSegmentMan()->updateFastestPeerStat(peerStat_);
  113. }
  114. namespace {
  115. void flushWrDiskCacheEntry(WrDiskCache* wrDiskCache,
  116. const std::shared_ptr<Segment>& segment)
  117. {
  118. const std::shared_ptr<Piece>& piece = segment->getPiece();
  119. if(piece->getWrDiskCacheEntry()) {
  120. piece->flushWrCache(wrDiskCache);
  121. if(piece->getWrDiskCacheEntry()->getError() !=
  122. WrDiskCacheEntry::CACHE_ERR_SUCCESS) {
  123. segment->clear(wrDiskCache);
  124. throw DOWNLOAD_FAILURE_EXCEPTION2
  125. (fmt("Write disk cache flush failure index=%lu",
  126. static_cast<unsigned long>(piece->getIndex())),
  127. piece->getWrDiskCacheEntry()->getErrorCode());
  128. }
  129. }
  130. }
  131. } // namespace
  132. bool DownloadCommand::executeInternal() {
  133. if(getDownloadEngine()->getRequestGroupMan()->doesOverallDownloadSpeedExceed()
  134. || getRequestGroup()->doesDownloadSpeedExceed()) {
  135. addCommandSelf();
  136. disableReadCheckSocket();
  137. return false;
  138. }
  139. setReadCheckSocket(getSocket());
  140. const std::shared_ptr<DiskAdaptor>& diskAdaptor =
  141. getPieceStorage()->getDiskAdaptor();
  142. std::shared_ptr<Segment> segment = getSegments().front();
  143. bool eof = false;
  144. if(getSocketRecvBuffer()->bufferEmpty()) {
  145. // Only read from socket when buffer is empty. Imagine that When
  146. // segment length is *short* and we are using HTTP pilelining. We
  147. // issued 2 requests in pipeline. When reading first response
  148. // header, we may read its response body and 2nd response header
  149. // and 2nd response body in buffer if they are small enough to fit
  150. // in buffer. And then server may sends EOF. In this case, we
  151. // read data from socket here, we will get EOF and leaves 2nd
  152. // response unprocessed. To prevent this, we don't read from
  153. // socket when buffer is not empty.
  154. eof = getSocketRecvBuffer()->recv() == 0 &&
  155. !getSocket()->wantRead() && !getSocket()->wantWrite();
  156. }
  157. if(!eof) {
  158. size_t bufSize;
  159. if(sinkFilterOnly_) {
  160. if(segment->getLength() > 0) {
  161. if(segment->getPosition()+segment->getLength() <=
  162. getFileEntry()->getLastOffset()) {
  163. bufSize =
  164. std::min(static_cast<size_t>(segment->getLength()
  165. -segment->getWrittenLength()),
  166. getSocketRecvBuffer()->getBufferLength());
  167. } else {
  168. bufSize =
  169. std::min
  170. (static_cast<size_t>
  171. (getFileEntry()->getLastOffset()-segment->getPositionToWrite()),
  172. getSocketRecvBuffer()->getBufferLength());
  173. }
  174. } else {
  175. bufSize = getSocketRecvBuffer()->getBufferLength();
  176. }
  177. streamFilter_->transform(diskAdaptor, segment,
  178. getSocketRecvBuffer()->getBuffer(), bufSize);
  179. } else {
  180. // It is possible that segment is completed but we have some bytes
  181. // of stream to read. For example, chunked encoding has "0"+CRLF
  182. // after data. After we read data(at this moment segment is
  183. // completed), we need another 3bytes(or more if it has trailers).
  184. streamFilter_->transform(diskAdaptor, segment,
  185. getSocketRecvBuffer()->getBuffer(),
  186. getSocketRecvBuffer()->getBufferLength());
  187. bufSize = streamFilter_->getBytesProcessed();
  188. }
  189. getSocketRecvBuffer()->shiftBuffer(bufSize);
  190. peerStat_->updateDownloadLength(bufSize);
  191. getDownloadContext()->updateDownloadLength(bufSize);
  192. }
  193. bool segmentPartComplete = false;
  194. // Note that GrowSegment::complete() always returns false.
  195. if(sinkFilterOnly_) {
  196. if(segment->complete() ||
  197. segment->getPositionToWrite() == getFileEntry()->getLastOffset()) {
  198. segmentPartComplete = true;
  199. } else if(segment->getLength() == 0 && eof) {
  200. segmentPartComplete = true;
  201. }
  202. } else {
  203. int64_t loff = getFileEntry()->gtoloff(segment->getPositionToWrite());
  204. if(getFileEntry()->getLength() > 0 && !sinkFilterOnly_ &&
  205. ((loff == getRequestEndOffset() && streamFilter_->finished())
  206. || loff < getRequestEndOffset()) &&
  207. (segment->complete() ||
  208. segment->getPositionToWrite() == getFileEntry()->getLastOffset())) {
  209. // In this case, StreamFilter other than *SinkStreamFilter is
  210. // used and Content-Length is known. We check
  211. // streamFilter_->finished() only if the requested end offset
  212. // equals to written position in file local offset; in other
  213. // words, data in the requested ranage is all received. If
  214. // requested end offset is greater than this segment, then
  215. // streamFilter_ is not finished in this segment.
  216. segmentPartComplete = true;
  217. } else if(streamFilter_->finished()) {
  218. segmentPartComplete = true;
  219. }
  220. }
  221. if(!segmentPartComplete && eof) {
  222. throw DL_RETRY_EX(EX_GOT_EOF);
  223. }
  224. if(segmentPartComplete) {
  225. if(segment->complete() || segment->getLength() == 0) {
  226. // If segment->getLength() == 0, the server doesn't provide
  227. // content length, but the client detected that download
  228. // completed.
  229. A2_LOG_INFO(fmt(MSG_SEGMENT_DOWNLOAD_COMPLETED,
  230. getCuid()));
  231. #ifdef ENABLE_MESSAGE_DIGEST
  232. {
  233. const std::string& expectedPieceHash =
  234. getDownloadContext()->getPieceHash(segment->getIndex());
  235. if(pieceHashValidationEnabled_ && !expectedPieceHash.empty()) {
  236. if(
  237. #ifdef ENABLE_BITTORRENT
  238. // TODO Is this necessary?
  239. (!getPieceStorage()->isEndGame() ||
  240. !getDownloadContext()->hasAttribute(CTX_ATTR_BT)) &&
  241. #endif // ENABLE_BITTORRENT
  242. segment->isHashCalculated()) {
  243. A2_LOG_DEBUG(fmt("Hash is available! index=%lu",
  244. static_cast<unsigned long>(segment->getIndex())));
  245. validatePieceHash
  246. (segment, expectedPieceHash, segment->getDigest());
  247. } else {
  248. try {
  249. std::string actualHash =
  250. segment->getPiece()->getDigestWithWrCache
  251. (segment->getSegmentLength(), diskAdaptor);
  252. validatePieceHash(segment, expectedPieceHash, actualHash);
  253. } catch(RecoverableException& e) {
  254. segment->clear(getPieceStorage()->getWrDiskCache());
  255. getSegmentMan()->cancelSegment(getCuid());
  256. throw;
  257. }
  258. }
  259. } else {
  260. completeSegment(getCuid(), segment);
  261. }
  262. }
  263. #else // !ENABLE_MESSAGE_DIGEST
  264. completeSegment(getCuid(), segment);
  265. #endif // !ENABLE_MESSAGE_DIGEST
  266. } else {
  267. // If segment is not canceled here, in the next pipelining
  268. // request, aria2 requests bad range
  269. // [FileEntry->getLastOffset(), FileEntry->getLastOffset())
  270. getSegmentMan()->cancelSegment(getCuid(), segment);
  271. }
  272. checkLowestDownloadSpeed();
  273. // this unit is going to download another segment.
  274. return prepareForNextSegment();
  275. } else {
  276. checkLowestDownloadSpeed();
  277. setWriteCheckSocketIf(getSocket(), getSocket()->wantWrite());
  278. checkSocketRecvBuffer();
  279. addCommandSelf();
  280. return false;
  281. }
  282. }
  283. void DownloadCommand::checkLowestDownloadSpeed() const
  284. {
  285. if(lowestDownloadSpeedLimit_ > 0 &&
  286. peerStat_->getDownloadStartTime().difference(global::wallclock()) >=
  287. startupIdleTime_) {
  288. int nowSpeed = peerStat_->calculateDownloadSpeed();
  289. if(nowSpeed <= lowestDownloadSpeedLimit_) {
  290. throw DL_ABORT_EX2(fmt(EX_TOO_SLOW_DOWNLOAD_SPEED,
  291. nowSpeed,
  292. lowestDownloadSpeedLimit_,
  293. getRequest()->getHost().c_str()),
  294. error_code::TOO_SLOW_DOWNLOAD_SPEED);
  295. }
  296. }
  297. }
  298. bool DownloadCommand::prepareForNextSegment() {
  299. if(getRequestGroup()->downloadFinished()) {
  300. // Remove in-flight request here.
  301. getFileEntry()->poolRequest(getRequest());
  302. // If this is a single file download, and file size becomes known
  303. // just after downloading, set total length to FileEntry object
  304. // here.
  305. if(getDownloadContext()->getFileEntries().size() == 1) {
  306. if(getFileEntry()->getLength() == 0) {
  307. getFileEntry()->setLength(getPieceStorage()->getCompletedLength());
  308. }
  309. }
  310. #ifdef ENABLE_MESSAGE_DIGEST
  311. if(getDownloadContext()->getPieceHashType().empty()) {
  312. auto entry = make_unique<ChecksumCheckIntegrityEntry>(getRequestGroup());
  313. if(entry->isValidationReady()) {
  314. entry->initValidator();
  315. entry->cutTrailingGarbage();
  316. getDownloadEngine()->getCheckIntegrityMan()->pushEntry
  317. (std::move(entry));
  318. }
  319. }
  320. #endif // ENABLE_MESSAGE_DIGEST
  321. // Following 2lines are needed for DownloadEngine to detect
  322. // completed RequestGroups without 1sec delay.
  323. getDownloadEngine()->setNoWait(true);
  324. getDownloadEngine()->setRefreshInterval(0);
  325. return true;
  326. } else {
  327. // The number of segments should be 1 in order to pass through the next
  328. // segment.
  329. if(getSegments().size() == 1) {
  330. std::shared_ptr<Segment> tempSegment = getSegments().front();
  331. if(!tempSegment->complete()) {
  332. return prepareForRetry(0);
  333. }
  334. if(getRequestEndOffset() ==
  335. getFileEntry()->gtoloff
  336. (tempSegment->getPosition()+tempSegment->getLength())) {
  337. return prepareForRetry(0);
  338. }
  339. std::shared_ptr<Segment> nextSegment = getSegmentMan()->getSegmentWithIndex
  340. (getCuid(), tempSegment->getIndex()+1);
  341. if(!nextSegment) {
  342. nextSegment = getSegmentMan()->getCleanSegmentIfOwnerIsIdle
  343. (getCuid(), tempSegment->getIndex()+1);
  344. }
  345. if(!nextSegment || nextSegment->getWrittenLength() > 0) {
  346. // If nextSegment->getWrittenLength() > 0, current socket must
  347. // be closed because writing incoming data at
  348. // nextSegment->getWrittenLength() corrupts file.
  349. return prepareForRetry(0);
  350. } else {
  351. checkSocketRecvBuffer();
  352. addCommandSelf();
  353. return false;
  354. }
  355. } else {
  356. return prepareForRetry(0);
  357. }
  358. }
  359. }
  360. #ifdef ENABLE_MESSAGE_DIGEST
  361. void DownloadCommand::validatePieceHash(const std::shared_ptr<Segment>& segment,
  362. const std::string& expectedHash,
  363. const std::string& actualHash)
  364. {
  365. if(actualHash == expectedHash) {
  366. A2_LOG_INFO(fmt(MSG_GOOD_CHUNK_CHECKSUM, util::toHex(actualHash).c_str()));
  367. completeSegment(getCuid(), segment);
  368. } else {
  369. A2_LOG_INFO(fmt(EX_INVALID_CHUNK_CHECKSUM,
  370. static_cast<unsigned long>(segment->getIndex()),
  371. segment->getPosition(),
  372. util::toHex(expectedHash).c_str(),
  373. util::toHex(actualHash).c_str()));
  374. segment->clear(getPieceStorage()->getWrDiskCache());
  375. getSegmentMan()->cancelSegment(getCuid());
  376. throw DL_RETRY_EX
  377. (fmt("Invalid checksum index=%lu",
  378. static_cast<unsigned long>(segment->getIndex())));
  379. }
  380. }
  381. #endif // ENABLE_MESSAGE_DIGEST
  382. void DownloadCommand::completeSegment(cuid_t cuid,
  383. const std::shared_ptr<Segment>& segment)
  384. {
  385. flushWrDiskCacheEntry(getPieceStorage()->getWrDiskCache(), segment);
  386. getSegmentMan()->completeSegment(cuid, segment);
  387. }
  388. void DownloadCommand::installStreamFilter
  389. (std::unique_ptr<StreamFilter> streamFilter)
  390. {
  391. if(!streamFilter) {
  392. return;
  393. }
  394. streamFilter->installDelegate(std::move(streamFilter_));
  395. streamFilter_ = std::move(streamFilter);
  396. const std::string& name = streamFilter_->getName();
  397. sinkFilterOnly_ = util::endsWith(name, SinkStreamFilter::NAME);
  398. }
  399. } // namespace aria2