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 <cerrno>
  37. #include <cstring>
  38. #include <fstream>
  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 "StringFormat.h"
  54. #include "array_fun.h"
  55. #include "DownloadContext.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. const std::string DefaultBtProgressInfoFile::V0000("0000");
  63. const std::string DefaultBtProgressInfoFile::V0001("0001");
  64. static 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. DefaultBtProgressInfoFile::DefaultBtProgressInfoFile
  72. (const SharedHandle<DownloadContext>& dctx,
  73. const PieceStorageHandle& pieceStorage,
  74. const Option* option):
  75. dctx_(dctx),
  76. pieceStorage_(pieceStorage),
  77. option_(option),
  78. logger_(LogFactory::getInstance()),
  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_.isNull();
  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. logger_->info(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(StringFormat(EX_SEGMENT_FILE_WRITE,
  103. filename_.c_str(), strerror(errno)).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[] = { 0x00, 0x01 };
  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(StringFormat(EX_SEGMENT_FILE_WRITE,
  190. filename_.c_str(), strerror(errno)).str());
  191. }
  192. logger_->info(MSG_SAVED_SEGMENT_FILE);
  193. }
  194. if(!File(filenameTemp).renameTo(filename_)) {
  195. throw DL_ABORT_EX(StringFormat(EX_SEGMENT_FILE_WRITE,
  196. filename_.c_str(), strerror(errno)).str());
  197. }
  198. }
  199. #define CHECK_STREAM(in, length) \
  200. if(in.gcount() != length) { \
  201. throw DL_ABORT_EX(StringFormat(EX_SEGMENT_FILE_READ, \
  202. filename_.c_str(),"Unexpected EOF").str()); \
  203. } \
  204. if(!in) { \
  205. throw DL_ABORT_EX(StringFormat(EX_SEGMENT_FILE_READ, \
  206. filename_.c_str(), strerror(errno)).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. logger_->info(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(StringFormat(EX_SEGMENT_FILE_READ, \
  217. filename_.c_str(), strerror(errno)).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. (StringFormat("Unsupported ctrl file version: %s",
  231. versionHex.c_str()).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. if(logger_->debug()) {
  240. logger_->debug("InfoHash checking enabled.");
  241. }
  242. }
  243. uint32_t infoHashLength;
  244. in.read(reinterpret_cast<char*>(&infoHashLength), sizeof(infoHashLength));
  245. CHECK_STREAM(in, sizeof(infoHashLength));
  246. if(version >= 1) {
  247. infoHashLength = ntohl(infoHashLength);
  248. }
  249. if((infoHashLength < 0) ||
  250. ((infoHashLength == 0) && infoHashCheckEnabled)) {
  251. throw DL_ABORT_EX
  252. (StringFormat("Invalid info hash length: %d", infoHashLength).str());
  253. }
  254. if(infoHashLength > 0) {
  255. array_ptr<unsigned char> savedInfoHash(new unsigned char[infoHashLength]);
  256. in.read(reinterpret_cast<char*>
  257. (static_cast<unsigned char*>(savedInfoHash)), infoHashLength);
  258. CHECK_STREAM(in, static_cast<int>(infoHashLength));
  259. #ifdef ENABLE_BITTORRENT
  260. if(infoHashCheckEnabled) {
  261. const unsigned char* infoHash = bittorrent::getInfoHash(dctx_);
  262. if(infoHashLength != INFO_HASH_LENGTH ||
  263. memcmp(savedInfoHash, infoHash, INFO_HASH_LENGTH) != 0) {
  264. throw DL_ABORT_EX
  265. (StringFormat("info hash mismatch. expected: %s, actual: %s",
  266. util::toHex(infoHash, INFO_HASH_LENGTH).c_str(),
  267. util::toHex(savedInfoHash, infoHashLength).c_str()
  268. ).str());
  269. }
  270. }
  271. #endif // ENABLE_BITTORRENT
  272. }
  273. uint32_t pieceLength;
  274. in.read(reinterpret_cast<char*>(&pieceLength), sizeof(pieceLength));
  275. CHECK_STREAM(in, sizeof(pieceLength));
  276. if(version >= 1) {
  277. pieceLength = ntohl(pieceLength);
  278. }
  279. uint64_t totalLength;
  280. in.read(reinterpret_cast<char*>(&totalLength), sizeof(totalLength));
  281. CHECK_STREAM(in, sizeof(totalLength));
  282. if(version >= 1) {
  283. totalLength = ntoh64(totalLength);
  284. }
  285. if(totalLength != dctx_->getTotalLength()) {
  286. throw DL_ABORT_EX
  287. (StringFormat("total length mismatch. expected: %s, actual: %s",
  288. util::itos(dctx_->getTotalLength()).c_str(),
  289. util::itos(totalLength).c_str()).str());
  290. }
  291. uint64_t uploadLength;
  292. in.read(reinterpret_cast<char*>(&uploadLength), sizeof(uploadLength));
  293. CHECK_STREAM(in, sizeof(uploadLength));
  294. if(version >= 1) {
  295. uploadLength = ntoh64(uploadLength);
  296. }
  297. #ifdef ENABLE_BITTORRENT
  298. if(isTorrentDownload()) {
  299. btRuntime_->setUploadLengthAtStartup(uploadLength);
  300. }
  301. #endif // ENABLE_BITTORRENT
  302. // TODO implement the conversion mechanism between different piece length.
  303. uint32_t bitfieldLength;
  304. in.read(reinterpret_cast<char*>(&bitfieldLength), sizeof(bitfieldLength));
  305. CHECK_STREAM(in, sizeof(bitfieldLength));
  306. if(version >= 1) {
  307. bitfieldLength = ntohl(bitfieldLength);
  308. }
  309. uint32_t expectedBitfieldLength =
  310. ((totalLength+pieceLength-1)/pieceLength+7)/8;
  311. if(expectedBitfieldLength != bitfieldLength) {
  312. throw DL_ABORT_EX
  313. (StringFormat("bitfield length mismatch. expected: %d, actual: %d",
  314. expectedBitfieldLength,
  315. bitfieldLength).str());
  316. }
  317. array_ptr<unsigned char> savedBitfield(new unsigned char[bitfieldLength]);
  318. in.read(reinterpret_cast<char*>
  319. (static_cast<unsigned char*>(savedBitfield)), bitfieldLength);
  320. CHECK_STREAM(in, static_cast<int>(bitfieldLength));
  321. if(pieceLength == dctx_->getPieceLength()) {
  322. pieceStorage_->setBitfield(savedBitfield, bitfieldLength);
  323. uint32_t numInFlightPiece;
  324. in.read(reinterpret_cast<char*>(&numInFlightPiece),
  325. sizeof(numInFlightPiece));
  326. CHECK_STREAM(in, sizeof(numInFlightPiece));
  327. if(version >= 1) {
  328. numInFlightPiece = ntohl(numInFlightPiece);
  329. }
  330. std::vector<SharedHandle<Piece> > inFlightPieces;
  331. inFlightPieces.reserve(numInFlightPiece);
  332. while(numInFlightPiece--) {
  333. uint32_t index;
  334. in.read(reinterpret_cast<char*>(&index), sizeof(index));
  335. CHECK_STREAM(in, sizeof(index));
  336. if(version >= 1) {
  337. index = ntohl(index);
  338. }
  339. if(!(index < dctx_->getNumPieces())) {
  340. throw DL_ABORT_EX
  341. (StringFormat("piece index out of range: %u", index).str());
  342. }
  343. uint32_t length;
  344. in.read(reinterpret_cast<char*>(&length), sizeof(length));
  345. CHECK_STREAM(in, sizeof(length));
  346. if(version >= 1) {
  347. length = ntohl(length);
  348. }
  349. if(!(length <=dctx_->getPieceLength())) {
  350. throw DL_ABORT_EX
  351. (StringFormat("piece length out of range: %u", length).str());
  352. }
  353. SharedHandle<Piece> piece(new Piece(index, length));
  354. uint32_t bitfieldLength;
  355. in.read(reinterpret_cast<char*>(&bitfieldLength),
  356. sizeof(bitfieldLength));
  357. CHECK_STREAM(in, sizeof(bitfieldLength));
  358. if(version >= 1) {
  359. bitfieldLength = ntohl(bitfieldLength);
  360. }
  361. if(piece->getBitfieldLength() != bitfieldLength) {
  362. throw DL_ABORT_EX
  363. (StringFormat("piece bitfield length mismatch."
  364. " expected: %u actual: %u",
  365. piece->getBitfieldLength(), bitfieldLength).str());
  366. }
  367. array_ptr<unsigned char> pieceBitfield
  368. (new unsigned char[bitfieldLength]);
  369. in.read(reinterpret_cast<char*>
  370. (static_cast<unsigned char*>(pieceBitfield)), bitfieldLength);
  371. CHECK_STREAM(in, static_cast<int>(bitfieldLength));
  372. piece->setBitfield(pieceBitfield, bitfieldLength);
  373. #ifdef ENABLE_MESSAGE_DIGEST
  374. piece->setHashAlgo(dctx_->getPieceHashAlgo());
  375. #endif // ENABLE_MESSAGE_DIGEST
  376. inFlightPieces.push_back(piece);
  377. }
  378. pieceStorage_->addInFlightPiece(inFlightPieces);
  379. } else {
  380. uint32_t numInFlightPiece;
  381. in.read(reinterpret_cast<char*>(&numInFlightPiece),
  382. sizeof(numInFlightPiece));
  383. CHECK_STREAM(in, sizeof(numInFlightPiece));
  384. if(version >= 1) {
  385. numInFlightPiece = ntohl(numInFlightPiece);
  386. }
  387. BitfieldMan src(pieceLength, totalLength);
  388. src.setBitfield(savedBitfield, bitfieldLength);
  389. if((src.getCompletedLength() || numInFlightPiece) &&
  390. !option_->getAsBool(PREF_ALLOW_PIECE_LENGTH_CHANGE)) {
  391. throw DOWNLOAD_FAILURE_EXCEPTION
  392. ("WARNING: Detected a change in piece length. You can proceed with"
  393. " --allow-piece-length-change=true, but you may lose some download"
  394. " progress.");
  395. }
  396. BitfieldMan dest(dctx_->getPieceLength(), totalLength);
  397. util::convertBitfield(&dest, &src);
  398. pieceStorage_->setBitfield(dest.getBitfield(), dest.getBitfieldLength());
  399. }
  400. logger_->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. logger_->info(MSG_SEGMENT_FILE_EXISTS, filename_.c_str());
  414. return true;
  415. } else {
  416. logger_->info(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