DefaultBtProgressInfoFile.cc 16 KB

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