DefaultBtProgressInfoFile.cc 16 KB

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