DefaultBtProgressInfoFile.cc 14 KB

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