DefaultBtProgressInfoFile.cc 14 KB

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