DefaultBtProgressInfoFile.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 "DefaultBtProgressInfoFile.h"
  36. #include <cstring>
  37. #include <cstdio>
  38. #include <array>
  39. #include "PieceStorage.h"
  40. #include "Piece.h"
  41. #include "BitfieldMan.h"
  42. #include "Option.h"
  43. #include "TransferStat.h"
  44. #include "LogFactory.h"
  45. #include "Logger.h"
  46. #include "prefs.h"
  47. #include "DlAbortEx.h"
  48. #include "message.h"
  49. #include "File.h"
  50. #include "util.h"
  51. #include "a2io.h"
  52. #include "DownloadFailureException.h"
  53. #include "fmt.h"
  54. #include "array_fun.h"
  55. #include "DownloadContext.h"
  56. #include "BufferedFile.h"
  57. #include "SHA1IOFile.h"
  58. #include "BtConstants.h"
  59. #ifdef ENABLE_BITTORRENT
  60. # include "PeerStorage.h"
  61. # include "BtRuntime.h"
  62. # include "bittorrent_helper.h"
  63. #endif // ENABLE_BITTORRENT
  64. namespace aria2 {
  65. namespace {
  66. std::string createFilename(const std::shared_ptr<DownloadContext>& dctx,
  67. const std::string& suffix)
  68. {
  69. std::string t = dctx->getBasePath();
  70. t += suffix;
  71. return t;
  72. }
  73. } // namespace
  74. DefaultBtProgressInfoFile::DefaultBtProgressInfoFile(
  75. const std::shared_ptr<DownloadContext>& dctx,
  76. const std::shared_ptr<PieceStorage>& pieceStorage, const Option* option)
  77. : dctx_(dctx),
  78. pieceStorage_(pieceStorage),
  79. option_(option),
  80. filename_(createFilename(dctx_, getSuffix()))
  81. {
  82. }
  83. DefaultBtProgressInfoFile::~DefaultBtProgressInfoFile() = default;
  84. void DefaultBtProgressInfoFile::updateFilename()
  85. {
  86. filename_ = createFilename(dctx_, getSuffix());
  87. }
  88. bool DefaultBtProgressInfoFile::isTorrentDownload()
  89. {
  90. #ifdef ENABLE_BITTORRENT
  91. return btRuntime_.get();
  92. #else // !ENABLE_BITTORRENT
  93. return false;
  94. #endif // !ENABLE_BITTORRENT
  95. }
  96. #define WRITE_CHECK(fp, ptr, count) \
  97. if (fp.write((ptr), (count)) != (count)) { \
  98. throw DL_ABORT_EX(fmt(EX_SEGMENT_FILE_WRITE, filename_.c_str())); \
  99. }
  100. // Since version 0001, Integers are saved in binary form, network byte order.
  101. void DefaultBtProgressInfoFile::save(IOFile& fp)
  102. {
  103. #ifdef ENABLE_BITTORRENT
  104. bool torrentDownload = isTorrentDownload();
  105. #else // !ENABLE_BITTORRENT
  106. bool torrentDownload = false;
  107. #endif // !ENABLE_BITTORRENT
  108. // file version: 16 bits
  109. // values: '1'
  110. char version[] = {0x00u, 0x01u};
  111. WRITE_CHECK(fp, version, sizeof(version));
  112. // extension: 32 bits
  113. // If this is BitTorrent download, then 0x00000001
  114. // Otherwise, 0x00000000
  115. char extension[4];
  116. memset(extension, 0, sizeof(extension));
  117. if (torrentDownload) {
  118. extension[3] = 1;
  119. }
  120. WRITE_CHECK(fp, extension, sizeof(extension));
  121. if (torrentDownload) {
  122. #ifdef ENABLE_BITTORRENT
  123. // infoHashLength:
  124. // length: 32 bits
  125. const unsigned char* infoHash = bittorrent::getInfoHash(dctx_);
  126. uint32_t infoHashLengthNL = htonl(INFO_HASH_LENGTH);
  127. WRITE_CHECK(fp, &infoHashLengthNL, sizeof(infoHashLengthNL));
  128. // infoHash:
  129. WRITE_CHECK(fp, infoHash, INFO_HASH_LENGTH);
  130. #endif // ENABLE_BITTORRENT
  131. }
  132. else {
  133. // infoHashLength:
  134. // length: 32 bits
  135. uint32_t infoHashLength = 0;
  136. WRITE_CHECK(fp, &infoHashLength, sizeof(infoHashLength));
  137. }
  138. // pieceLength: 32 bits
  139. uint32_t pieceLengthNL = htonl(dctx_->getPieceLength());
  140. WRITE_CHECK(fp, &pieceLengthNL, sizeof(pieceLengthNL));
  141. // totalLength: 64 bits
  142. uint64_t totalLengthNL = hton64(dctx_->getTotalLength());
  143. WRITE_CHECK(fp, &totalLengthNL, sizeof(totalLengthNL));
  144. // uploadLength: 64 bits
  145. uint64_t uploadLengthNL = 0;
  146. #ifdef ENABLE_BITTORRENT
  147. if (torrentDownload) {
  148. uploadLengthNL = hton64(btRuntime_->getUploadLengthAtStartup() +
  149. dctx_->getNetStat().getSessionUploadLength());
  150. }
  151. #endif // ENABLE_BITTORRENT
  152. WRITE_CHECK(fp, &uploadLengthNL, sizeof(uploadLengthNL));
  153. // bitfieldLength: 32 bits
  154. uint32_t bitfieldLengthNL = htonl(pieceStorage_->getBitfieldLength());
  155. WRITE_CHECK(fp, &bitfieldLengthNL, sizeof(bitfieldLengthNL));
  156. // bitfield
  157. WRITE_CHECK(fp, pieceStorage_->getBitfield(),
  158. pieceStorage_->getBitfieldLength());
  159. // the number of in-flight piece: 32 bits
  160. // TODO implement this
  161. uint32_t numInFlightPieceNL = htonl(pieceStorage_->countInFlightPiece());
  162. WRITE_CHECK(fp, &numInFlightPieceNL, sizeof(numInFlightPieceNL));
  163. std::vector<std::shared_ptr<Piece>> inFlightPieces;
  164. inFlightPieces.reserve(pieceStorage_->countInFlightPiece());
  165. pieceStorage_->getInFlightPieces(inFlightPieces);
  166. for (std::vector<std::shared_ptr<Piece>>::const_iterator
  167. itr = inFlightPieces.begin(),
  168. eoi = inFlightPieces.end();
  169. itr != eoi; ++itr) {
  170. uint32_t indexNL = htonl((*itr)->getIndex());
  171. WRITE_CHECK(fp, &indexNL, sizeof(indexNL));
  172. uint32_t lengthNL = htonl((*itr)->getLength());
  173. WRITE_CHECK(fp, &lengthNL, sizeof(lengthNL));
  174. uint32_t bitfieldLengthNL = htonl((*itr)->getBitfieldLength());
  175. WRITE_CHECK(fp, &bitfieldLengthNL, sizeof(bitfieldLengthNL));
  176. WRITE_CHECK(fp, (*itr)->getBitfield(), (*itr)->getBitfieldLength());
  177. }
  178. if (fp.close() == EOF) {
  179. throw DL_ABORT_EX(fmt(EX_SEGMENT_FILE_WRITE, filename_.c_str()));
  180. }
  181. }
  182. void DefaultBtProgressInfoFile::save()
  183. {
  184. SHA1IOFile sha1io;
  185. save(sha1io);
  186. auto digest = sha1io.digest();
  187. if (digest == lastDigest_) {
  188. // We don't write control file if the content is not changed.
  189. return;
  190. }
  191. lastDigest_ = std::move(digest);
  192. A2_LOG_INFO(fmt(MSG_SAVING_SEGMENT_FILE, filename_.c_str()));
  193. std::string filenameTemp = filename_;
  194. filenameTemp += "__temp";
  195. {
  196. BufferedFile fp(filenameTemp.c_str(), BufferedFile::WRITE);
  197. if (!fp) {
  198. throw DL_ABORT_EX(fmt(EX_SEGMENT_FILE_WRITE, filename_.c_str()));
  199. }
  200. save(fp);
  201. }
  202. A2_LOG_INFO(MSG_SAVED_SEGMENT_FILE);
  203. if (!File(filenameTemp).renameTo(filename_)) {
  204. throw DL_ABORT_EX(fmt(EX_SEGMENT_FILE_WRITE, filename_.c_str()));
  205. }
  206. }
  207. #define READ_CHECK(fp, ptr, count) \
  208. if (fp.read((ptr), (count)) != (count)) { \
  209. throw DL_ABORT_EX(fmt(EX_SEGMENT_FILE_READ, filename_.c_str())); \
  210. }
  211. // It is assumed that integers are saved as:
  212. // 1) host byte order if version == 0000
  213. // 2) network byte order if version == 0001
  214. void DefaultBtProgressInfoFile::load()
  215. {
  216. A2_LOG_INFO(fmt(MSG_LOADING_SEGMENT_FILE, filename_.c_str()));
  217. BufferedFile fp(filename_.c_str(), BufferedFile::READ);
  218. if (!fp) {
  219. throw DL_ABORT_EX(fmt(EX_SEGMENT_FILE_READ, filename_.c_str()));
  220. }
  221. unsigned char versionBuf[2];
  222. READ_CHECK(fp, versionBuf, sizeof(versionBuf));
  223. std::string versionHex = util::toHex(versionBuf, sizeof(versionBuf));
  224. int version;
  225. if ("0000" == versionHex) {
  226. version = 0;
  227. }
  228. else if ("0001" == versionHex) {
  229. version = 1;
  230. }
  231. else {
  232. throw DL_ABORT_EX(
  233. fmt("Unsupported ctrl file version: %s", versionHex.c_str()));
  234. }
  235. unsigned char extension[4];
  236. READ_CHECK(fp, extension, sizeof(extension));
  237. bool infoHashCheckEnabled = false;
  238. if (extension[3] & 1 && isTorrentDownload()) {
  239. infoHashCheckEnabled = true;
  240. A2_LOG_DEBUG("InfoHash checking enabled.");
  241. }
  242. uint32_t infoHashLength;
  243. READ_CHECK(fp, &infoHashLength, sizeof(infoHashLength));
  244. if (version >= 1) {
  245. infoHashLength = ntohl(infoHashLength);
  246. }
  247. if (infoHashLength > INFO_HASH_LENGTH ||
  248. (infoHashLength != INFO_HASH_LENGTH && infoHashCheckEnabled)) {
  249. throw DL_ABORT_EX(fmt("Invalid info hash length: %d", infoHashLength));
  250. }
  251. if (infoHashLength > 0) {
  252. std::array<unsigned char, INFO_HASH_LENGTH> savedInfoHash;
  253. READ_CHECK(fp, savedInfoHash.data(), infoHashLength);
  254. #ifdef ENABLE_BITTORRENT
  255. if (infoHashCheckEnabled) {
  256. const unsigned char* infoHash = bittorrent::getInfoHash(dctx_);
  257. if (memcmp(savedInfoHash.data(), infoHash, INFO_HASH_LENGTH) != 0) {
  258. throw DL_ABORT_EX(
  259. fmt("info hash mismatch. expected: %s, actual: %s",
  260. util::toHex(infoHash, INFO_HASH_LENGTH).c_str(),
  261. util::toHex(savedInfoHash.data(), infoHashLength).c_str()));
  262. }
  263. }
  264. #endif // ENABLE_BITTORRENT
  265. }
  266. uint32_t pieceLength;
  267. READ_CHECK(fp, &pieceLength, sizeof(pieceLength));
  268. if (version >= 1) {
  269. pieceLength = ntohl(pieceLength);
  270. }
  271. if (pieceLength == 0) {
  272. throw DL_ABORT_EX("piece length must not be 0");
  273. }
  274. uint64_t totalLength;
  275. READ_CHECK(fp, &totalLength, sizeof(totalLength));
  276. if (version >= 1) {
  277. totalLength = ntoh64(totalLength);
  278. }
  279. if (totalLength != static_cast<uint64_t>(dctx_->getTotalLength())) {
  280. throw DL_ABORT_EX(
  281. fmt("total length mismatch. expected: %" PRId64 ", actual: %" PRId64 "",
  282. dctx_->getTotalLength(), static_cast<int64_t>(totalLength)));
  283. }
  284. uint64_t uploadLength;
  285. READ_CHECK(fp, &uploadLength, sizeof(uploadLength));
  286. if (version >= 1) {
  287. uploadLength = ntoh64(uploadLength);
  288. }
  289. #ifdef ENABLE_BITTORRENT
  290. if (isTorrentDownload()) {
  291. btRuntime_->setUploadLengthAtStartup(uploadLength);
  292. }
  293. #endif // ENABLE_BITTORRENT
  294. // TODO implement the conversion mechanism between different piece length.
  295. uint32_t bitfieldLength;
  296. READ_CHECK(fp, &bitfieldLength, sizeof(bitfieldLength));
  297. if (version >= 1) {
  298. bitfieldLength = ntohl(bitfieldLength);
  299. }
  300. uint32_t expectedBitfieldLength =
  301. ((totalLength + pieceLength - 1) / pieceLength + 7) / 8;
  302. if (expectedBitfieldLength != bitfieldLength) {
  303. throw DL_ABORT_EX(fmt("bitfield length mismatch. expected: %d, actual: %d",
  304. expectedBitfieldLength, bitfieldLength));
  305. }
  306. auto savedBitfield = make_unique<unsigned char[]>((size_t)bitfieldLength);
  307. READ_CHECK(fp, savedBitfield.get(), bitfieldLength);
  308. if (pieceLength == static_cast<uint32_t>(dctx_->getPieceLength())) {
  309. pieceStorage_->setBitfield(savedBitfield.get(), bitfieldLength);
  310. uint32_t numInFlightPiece;
  311. READ_CHECK(fp, &numInFlightPiece, sizeof(numInFlightPiece));
  312. if (version >= 1) {
  313. numInFlightPiece = ntohl(numInFlightPiece);
  314. }
  315. std::vector<std::shared_ptr<Piece>> inFlightPieces;
  316. inFlightPieces.reserve(numInFlightPiece);
  317. while (numInFlightPiece--) {
  318. uint32_t index;
  319. READ_CHECK(fp, &index, sizeof(index));
  320. if (version >= 1) {
  321. index = ntohl(index);
  322. }
  323. if (!(index < dctx_->getNumPieces())) {
  324. throw DL_ABORT_EX(fmt("piece index out of range: %u", index));
  325. }
  326. uint32_t length;
  327. READ_CHECK(fp, &length, sizeof(length));
  328. if (version >= 1) {
  329. length = ntohl(length);
  330. }
  331. if (!(length <= static_cast<uint32_t>(dctx_->getPieceLength()))) {
  332. throw DL_ABORT_EX(fmt("piece length out of range: %u", length));
  333. }
  334. auto piece = std::make_shared<Piece>(index, length);
  335. uint32_t bitfieldLength;
  336. READ_CHECK(fp, &bitfieldLength, sizeof(bitfieldLength));
  337. if (version >= 1) {
  338. bitfieldLength = ntohl(bitfieldLength);
  339. }
  340. if (piece->getBitfieldLength() != bitfieldLength) {
  341. throw DL_ABORT_EX(
  342. fmt("piece bitfield length mismatch."
  343. " expected: %lu actual: %u",
  344. static_cast<unsigned long>(piece->getBitfieldLength()),
  345. bitfieldLength));
  346. }
  347. auto pieceBitfield = make_unique<unsigned char[]>((size_t)bitfieldLength);
  348. READ_CHECK(fp, pieceBitfield.get(), bitfieldLength);
  349. piece->setBitfield(pieceBitfield.get(), bitfieldLength);
  350. piece->setHashType(dctx_->getPieceHashType());
  351. inFlightPieces.push_back(piece);
  352. }
  353. pieceStorage_->addInFlightPiece(inFlightPieces);
  354. }
  355. else {
  356. uint32_t numInFlightPiece;
  357. READ_CHECK(fp, &numInFlightPiece, sizeof(numInFlightPiece));
  358. if (version >= 1) {
  359. numInFlightPiece = ntohl(numInFlightPiece);
  360. }
  361. BitfieldMan src(pieceLength, totalLength);
  362. src.setBitfield(savedBitfield.get(), bitfieldLength);
  363. if ((src.getCompletedLength() || numInFlightPiece) &&
  364. !option_->getAsBool(PREF_ALLOW_PIECE_LENGTH_CHANGE)) {
  365. throw DOWNLOAD_FAILURE_EXCEPTION2(
  366. "WARNING: Detected a change in piece length. You can proceed with"
  367. " --allow-piece-length-change=true, but you may lose some download"
  368. " progress.",
  369. error_code::PIECE_LENGTH_CHANGED);
  370. }
  371. BitfieldMan dest(dctx_->getPieceLength(), totalLength);
  372. util::convertBitfield(&dest, &src);
  373. pieceStorage_->setBitfield(dest.getBitfield(), dest.getBitfieldLength());
  374. }
  375. A2_LOG_INFO(MSG_LOADED_SEGMENT_FILE);
  376. }
  377. void DefaultBtProgressInfoFile::removeFile()
  378. {
  379. if (exists()) {
  380. File f(filename_);
  381. f.remove();
  382. }
  383. }
  384. bool DefaultBtProgressInfoFile::exists()
  385. {
  386. File f(filename_);
  387. if (f.isFile()) {
  388. A2_LOG_INFO(fmt(MSG_SEGMENT_FILE_EXISTS, filename_.c_str()));
  389. return true;
  390. }
  391. else {
  392. A2_LOG_INFO(fmt(MSG_SEGMENT_FILE_DOES_NOT_EXIST, filename_.c_str()));
  393. return false;
  394. }
  395. }
  396. #ifdef ENABLE_BITTORRENT
  397. void DefaultBtProgressInfoFile::setPeerStorage(
  398. const std::shared_ptr<PeerStorage>& peerStorage)
  399. {
  400. peerStorage_ = peerStorage;
  401. }
  402. void DefaultBtProgressInfoFile::setBtRuntime(
  403. const std::shared_ptr<BtRuntime>& btRuntime)
  404. {
  405. btRuntime_ = btRuntime;
  406. }
  407. #endif // ENABLE_BITTORRENT
  408. } // namespace aria2