DefaultBtProgressInfoFile.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. Pieces inFlightPieces;
  172. _pieceStorage->getInFlightPieces(inFlightPieces);
  173. for(Pieces::const_iterator itr = inFlightPieces.begin();
  174. itr != inFlightPieces.end(); ++itr) {
  175. uint32_t indexNL = htonl((*itr)->getIndex());
  176. o.write(reinterpret_cast<const char*>(&indexNL), sizeof(indexNL));
  177. uint32_t lengthNL = htonl((*itr)->getLength());
  178. o.write(reinterpret_cast<const char*>(&lengthNL), sizeof(lengthNL));
  179. uint32_t bitfieldLengthNL = htonl((*itr)->getBitfieldLength());
  180. o.write(reinterpret_cast<const char*>(&bitfieldLengthNL),
  181. sizeof(bitfieldLengthNL));
  182. o.write(reinterpret_cast<const char*>((*itr)->getBitfield()),
  183. (*itr)->getBitfieldLength());
  184. }
  185. o.flush();
  186. if(!o) {
  187. throw DL_ABORT_EX(StringFormat(EX_SEGMENT_FILE_WRITE,
  188. _filename.c_str(), strerror(errno)).str());
  189. }
  190. _logger->info(MSG_SAVED_SEGMENT_FILE);
  191. }
  192. if(!File(filenameTemp).renameTo(_filename)) {
  193. throw DL_ABORT_EX(StringFormat(EX_SEGMENT_FILE_WRITE,
  194. _filename.c_str(), strerror(errno)).str());
  195. }
  196. }
  197. #define CHECK_STREAM(in, length) \
  198. if(in.gcount() != length) { \
  199. throw DL_ABORT_EX(StringFormat(EX_SEGMENT_FILE_READ, \
  200. _filename.c_str(),"Unexpected EOF").str()); \
  201. } \
  202. if(!in) { \
  203. throw DL_ABORT_EX(StringFormat(EX_SEGMENT_FILE_READ, \
  204. _filename.c_str(), strerror(errno)).str()); \
  205. }
  206. // It is assumed that integers are saved as:
  207. // 1) host byte order if version == 0000
  208. // 2) network byte order if version == 0001
  209. void DefaultBtProgressInfoFile::load()
  210. {
  211. _logger->info(MSG_LOADING_SEGMENT_FILE, _filename.c_str());
  212. std::ifstream in(_filename.c_str(), std::ios::in|std::ios::binary);
  213. if(!in) { \
  214. throw DL_ABORT_EX(StringFormat(EX_SEGMENT_FILE_READ, \
  215. _filename.c_str(), strerror(errno)).str());
  216. }
  217. unsigned char versionBuf[2];
  218. in.read(reinterpret_cast<char*>(versionBuf), sizeof(versionBuf));
  219. CHECK_STREAM(in, sizeof(versionBuf));
  220. std::string versionHex = util::toHex(versionBuf, sizeof(versionBuf));
  221. int version;
  222. if(DefaultBtProgressInfoFile::V0000 == versionHex) {
  223. version = 0;
  224. } else if(DefaultBtProgressInfoFile::V0001 == versionHex) {
  225. version = 1;
  226. } else {
  227. throw DL_ABORT_EX
  228. (StringFormat("Unsupported ctrl file version: %s",
  229. versionHex.c_str()).str());
  230. }
  231. unsigned char extension[4];
  232. in.read(reinterpret_cast<char*>(extension), sizeof(extension));
  233. CHECK_STREAM(in, sizeof(extension));
  234. bool infoHashCheckEnabled = false;
  235. if(extension[3]&1 && isTorrentDownload()) {
  236. infoHashCheckEnabled = true;
  237. _logger->debug("InfoHash checking enabled.");
  238. }
  239. uint32_t infoHashLength;
  240. in.read(reinterpret_cast<char*>(&infoHashLength), sizeof(infoHashLength));
  241. CHECK_STREAM(in, sizeof(infoHashLength));
  242. if(version >= 1) {
  243. infoHashLength = ntohl(infoHashLength);
  244. }
  245. if((infoHashLength < 0) ||
  246. ((infoHashLength == 0) && infoHashCheckEnabled)) {
  247. throw DL_ABORT_EX
  248. (StringFormat("Invalid info hash length: %d", infoHashLength).str());
  249. }
  250. if(infoHashLength > 0) {
  251. array_ptr<unsigned char> savedInfoHash(new unsigned char[infoHashLength]);
  252. in.read(reinterpret_cast<char*>
  253. (static_cast<unsigned char*>(savedInfoHash)), infoHashLength);
  254. CHECK_STREAM(in, static_cast<int>(infoHashLength));
  255. #ifdef ENABLE_BITTORRENT
  256. if(infoHashCheckEnabled) {
  257. const unsigned char* infoHash = bittorrent::getInfoHash(_dctx);
  258. if(infoHashLength != INFO_HASH_LENGTH ||
  259. memcmp(savedInfoHash, infoHash, INFO_HASH_LENGTH) != 0) {
  260. throw DL_ABORT_EX
  261. (StringFormat("info hash mismatch. expected: %s, actual: %s",
  262. util::toHex(infoHash, INFO_HASH_LENGTH).c_str(),
  263. util::toHex(savedInfoHash, infoHashLength).c_str()
  264. ).str());
  265. }
  266. }
  267. #endif // ENABLE_BITTORRENT
  268. }
  269. uint32_t pieceLength;
  270. in.read(reinterpret_cast<char*>(&pieceLength), sizeof(pieceLength));
  271. CHECK_STREAM(in, sizeof(pieceLength));
  272. if(version >= 1) {
  273. pieceLength = ntohl(pieceLength);
  274. }
  275. uint64_t totalLength;
  276. in.read(reinterpret_cast<char*>(&totalLength), sizeof(totalLength));
  277. CHECK_STREAM(in, sizeof(totalLength));
  278. if(version >= 1) {
  279. totalLength = ntoh64(totalLength);
  280. }
  281. if(totalLength != _dctx->getTotalLength()) {
  282. throw DL_ABORT_EX
  283. (StringFormat("total length mismatch. expected: %s, actual: %s",
  284. util::itos(_dctx->getTotalLength()).c_str(),
  285. util::itos(totalLength).c_str()).str());
  286. }
  287. uint64_t uploadLength;
  288. in.read(reinterpret_cast<char*>(&uploadLength), sizeof(uploadLength));
  289. CHECK_STREAM(in, sizeof(uploadLength));
  290. if(version >= 1) {
  291. uploadLength = ntoh64(uploadLength);
  292. }
  293. #ifdef ENABLE_BITTORRENT
  294. if(isTorrentDownload()) {
  295. _btRuntime->setUploadLengthAtStartup(uploadLength);
  296. }
  297. #endif // ENABLE_BITTORRENT
  298. // TODO implement the conversion mechanism between different piece length.
  299. uint32_t bitfieldLength;
  300. in.read(reinterpret_cast<char*>(&bitfieldLength), sizeof(bitfieldLength));
  301. CHECK_STREAM(in, sizeof(bitfieldLength));
  302. if(version >= 1) {
  303. bitfieldLength = ntohl(bitfieldLength);
  304. }
  305. uint32_t expectedBitfieldLength =
  306. ((totalLength+pieceLength-1)/pieceLength+7)/8;
  307. if(expectedBitfieldLength != bitfieldLength) {
  308. throw DL_ABORT_EX
  309. (StringFormat("bitfield length mismatch. expected: %d, actual: %d",
  310. expectedBitfieldLength,
  311. bitfieldLength).str());
  312. }
  313. array_ptr<unsigned char> savedBitfield(new unsigned char[bitfieldLength]);
  314. in.read(reinterpret_cast<char*>
  315. (static_cast<unsigned char*>(savedBitfield)), bitfieldLength);
  316. CHECK_STREAM(in, static_cast<int>(bitfieldLength));
  317. if(pieceLength == _dctx->getPieceLength()) {
  318. _pieceStorage->setBitfield(savedBitfield, bitfieldLength);
  319. uint32_t numInFlightPiece;
  320. in.read(reinterpret_cast<char*>(&numInFlightPiece),
  321. sizeof(numInFlightPiece));
  322. CHECK_STREAM(in, sizeof(numInFlightPiece));
  323. if(version >= 1) {
  324. numInFlightPiece = ntohl(numInFlightPiece);
  325. }
  326. Pieces inFlightPieces;
  327. while(numInFlightPiece--) {
  328. uint32_t index;
  329. in.read(reinterpret_cast<char*>(&index), sizeof(index));
  330. CHECK_STREAM(in, sizeof(index));
  331. if(version >= 1) {
  332. index = ntohl(index);
  333. }
  334. if(!(index < _dctx->getNumPieces())) {
  335. throw DL_ABORT_EX
  336. (StringFormat("piece index out of range: %u", index).str());
  337. }
  338. uint32_t length;
  339. in.read(reinterpret_cast<char*>(&length), sizeof(length));
  340. CHECK_STREAM(in, sizeof(length));
  341. if(version >= 1) {
  342. length = ntohl(length);
  343. }
  344. if(!(length <=_dctx->getPieceLength())) {
  345. throw DL_ABORT_EX
  346. (StringFormat("piece length out of range: %u", length).str());
  347. }
  348. PieceHandle piece(new Piece(index, length));
  349. uint32_t bitfieldLength;
  350. in.read(reinterpret_cast<char*>(&bitfieldLength),
  351. sizeof(bitfieldLength));
  352. CHECK_STREAM(in, sizeof(bitfieldLength));
  353. if(version >= 1) {
  354. bitfieldLength = ntohl(bitfieldLength);
  355. }
  356. if(piece->getBitfieldLength() != bitfieldLength) {
  357. throw DL_ABORT_EX
  358. (StringFormat("piece bitfield length mismatch."
  359. " expected: %u actual: %u",
  360. piece->getBitfieldLength(), bitfieldLength).str());
  361. }
  362. array_ptr<unsigned char> pieceBitfield
  363. (new unsigned char[bitfieldLength]);
  364. in.read(reinterpret_cast<char*>
  365. (static_cast<unsigned char*>(pieceBitfield)), bitfieldLength);
  366. CHECK_STREAM(in, static_cast<int>(bitfieldLength));
  367. piece->setBitfield(pieceBitfield, bitfieldLength);
  368. #ifdef ENABLE_MESSAGE_DIGEST
  369. piece->setHashAlgo(_dctx->getPieceHashAlgo());
  370. #endif // ENABLE_MESSAGE_DIGEST
  371. inFlightPieces.push_back(piece);
  372. }
  373. _pieceStorage->addInFlightPiece(inFlightPieces);
  374. } else {
  375. uint32_t numInFlightPiece;
  376. in.read(reinterpret_cast<char*>(&numInFlightPiece),
  377. sizeof(numInFlightPiece));
  378. CHECK_STREAM(in, sizeof(numInFlightPiece));
  379. if(version >= 1) {
  380. numInFlightPiece = ntohl(numInFlightPiece);
  381. }
  382. BitfieldMan src(pieceLength, totalLength);
  383. src.setBitfield(savedBitfield, bitfieldLength);
  384. if((src.getCompletedLength() || numInFlightPiece) &&
  385. !_option->getAsBool(PREF_ALLOW_PIECE_LENGTH_CHANGE)) {
  386. throw DOWNLOAD_FAILURE_EXCEPTION
  387. ("WARNING: Detected a change in piece length. You can proceed with"
  388. " --allow-piece-length-change=true, but you may lose some download"
  389. " progress.");
  390. }
  391. BitfieldMan dest(_dctx->getPieceLength(), totalLength);
  392. util::convertBitfield(&dest, &src);
  393. _pieceStorage->setBitfield(dest.getBitfield(), dest.getBitfieldLength());
  394. }
  395. _logger->info(MSG_LOADED_SEGMENT_FILE);
  396. }
  397. void DefaultBtProgressInfoFile::removeFile()
  398. {
  399. if(exists()) {
  400. File f(_filename);
  401. f.remove();
  402. }
  403. }
  404. bool DefaultBtProgressInfoFile::exists()
  405. {
  406. File f(_filename);
  407. if(f.isFile()) {
  408. _logger->info(MSG_SEGMENT_FILE_EXISTS, _filename.c_str());
  409. return true;
  410. } else {
  411. _logger->info(MSG_SEGMENT_FILE_DOES_NOT_EXIST, _filename.c_str());
  412. return false;
  413. }
  414. }
  415. #ifdef ENABLE_BITTORRENT
  416. void DefaultBtProgressInfoFile::setPeerStorage
  417. (const SharedHandle<PeerStorage>& peerStorage)
  418. {
  419. _peerStorage = peerStorage;
  420. }
  421. void DefaultBtProgressInfoFile::setBtRuntime
  422. (const SharedHandle<BtRuntime>& btRuntime)
  423. {
  424. _btRuntime = btRuntime;
  425. }
  426. #endif // ENABLE_BITTORRENT
  427. } // namespace aria2