DownloadCommand.cc 16 KB

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