DefaultBtProgressInfoFile.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 "BtContext.h"
  40. #include "PieceStorage.h"
  41. #include "Piece.h"
  42. #ifdef ENABLE_BITTORRENT
  43. #include "PeerStorage.h"
  44. #include "BtRuntime.h"
  45. #endif // ENABLE_BITTORRENT
  46. #include "BitfieldMan.h"
  47. #include "Option.h"
  48. #include "TransferStat.h"
  49. #include "LogFactory.h"
  50. #include "Logger.h"
  51. #include "prefs.h"
  52. #include "DlAbortEx.h"
  53. #include "message.h"
  54. #include "File.h"
  55. #include "Util.h"
  56. #include "a2io.h"
  57. #include "DownloadFailureException.h"
  58. #include "StringFormat.h"
  59. namespace aria2 {
  60. const std::string DefaultBtProgressInfoFile::V0000("0000");
  61. const std::string DefaultBtProgressInfoFile::V0001("0001");
  62. static std::string createFilename(const SharedHandle<DownloadContext>& dctx)
  63. {
  64. return dctx->getActualBasePath()+".aria2";
  65. }
  66. DefaultBtProgressInfoFile::DefaultBtProgressInfoFile
  67. (const DownloadContextHandle& dctx,
  68. const PieceStorageHandle& pieceStorage,
  69. const Option* option):
  70. _dctx(dctx),
  71. _pieceStorage(pieceStorage),
  72. _option(option),
  73. _logger(LogFactory::getInstance()),
  74. _filename(createFilename(_dctx))
  75. {}
  76. DefaultBtProgressInfoFile::~DefaultBtProgressInfoFile() {}
  77. void DefaultBtProgressInfoFile::updateFilename()
  78. {
  79. _filename = createFilename(_dctx);
  80. }
  81. bool DefaultBtProgressInfoFile::isTorrentDownload()
  82. {
  83. #ifdef ENABLE_BITTORRENT
  84. return !_btRuntime.isNull();
  85. #else // !ENABLE_BITTORRENT
  86. return false;
  87. #endif // !ENABLE_BITTORRENT
  88. }
  89. // Since version 0001, Integers are saved in binary form, network byte order.
  90. void DefaultBtProgressInfoFile::save() {
  91. _logger->info(MSG_SAVING_SEGMENT_FILE, _filename.c_str());
  92. std::string filenameTemp = _filename+"__temp";
  93. std::ofstream o(filenameTemp.c_str(), std::ios::out|std::ios::binary);
  94. try {
  95. o.exceptions(std::ios::failbit);
  96. bool torrentDownload = isTorrentDownload();
  97. // file version: 16 bits
  98. // values: '1'
  99. char version[] = { 0x00, 0x01 };
  100. o.write(version, sizeof(version));
  101. // extension: 32 bits
  102. // If this is BitTorrent download, then 0x00000001
  103. // Otherwise, 0x00000000
  104. char extension[4];
  105. memset(extension, 0, sizeof(extension));
  106. if(torrentDownload) {
  107. extension[3] = 1;
  108. }
  109. o.write(reinterpret_cast<const char*>(&extension), sizeof(extension));
  110. if(torrentDownload) {
  111. // infoHashLength:
  112. // length: 32 bits
  113. BtContextHandle btContext(dynamic_pointer_cast<BtContext>(_dctx));
  114. uint32_t infoHashLengthNL = htonl(btContext->getInfoHashLength());
  115. o.write(reinterpret_cast<const char*>(&infoHashLengthNL),
  116. sizeof(infoHashLengthNL));
  117. // infoHash:
  118. o.write(reinterpret_cast<const char*>(btContext->getInfoHash()),
  119. btContext->getInfoHashLength());
  120. } else {
  121. // infoHashLength:
  122. // length: 32 bits
  123. uint32_t infoHashLength = 0;
  124. o.write(reinterpret_cast<const char*>(&infoHashLength),
  125. sizeof(infoHashLength));
  126. }
  127. // pieceLength: 32 bits
  128. uint32_t pieceLengthNL = htonl(_dctx->getPieceLength());
  129. o.write(reinterpret_cast<const char*>(&pieceLengthNL),
  130. sizeof(pieceLengthNL));
  131. // totalLength: 64 bits
  132. uint64_t totalLengthNL = hton64(_dctx->getTotalLength());
  133. o.write(reinterpret_cast<const char*>(&totalLengthNL),
  134. sizeof(totalLengthNL));
  135. // uploadLength: 64 bits
  136. uint64_t uploadLengthNL = 0;
  137. #ifdef ENABLE_BITTORRENT
  138. if(torrentDownload) {
  139. TransferStat stat = _peerStorage->calculateStat();
  140. uploadLengthNL = hton64(stat.getAllTimeUploadLength());
  141. }
  142. #endif // ENABLE_BITTORRENT
  143. o.write(reinterpret_cast<const char*>(&uploadLengthNL),
  144. sizeof(uploadLengthNL));
  145. // bitfieldLength: 32 bits
  146. uint32_t bitfieldLengthNL = htonl(_pieceStorage->getBitfieldLength());
  147. o.write(reinterpret_cast<const char*>(&bitfieldLengthNL),
  148. sizeof(bitfieldLengthNL));
  149. // bitfield
  150. o.write(reinterpret_cast<const char*>(_pieceStorage->getBitfield()),
  151. _pieceStorage->getBitfieldLength());
  152. // the number of in-flight piece: 32 bits
  153. // TODO implement this
  154. uint32_t numInFlightPieceNL = htonl(_pieceStorage->countInFlightPiece());
  155. o.write(reinterpret_cast<const char*>(&numInFlightPieceNL),
  156. sizeof(numInFlightPieceNL));
  157. Pieces inFlightPieces;
  158. _pieceStorage->getInFlightPieces(inFlightPieces);
  159. for(Pieces::const_iterator itr = inFlightPieces.begin();
  160. itr != inFlightPieces.end(); ++itr) {
  161. uint32_t indexNL = htonl((*itr)->getIndex());
  162. o.write(reinterpret_cast<const char*>(&indexNL), sizeof(indexNL));
  163. uint32_t lengthNL = htonl((*itr)->getLength());
  164. o.write(reinterpret_cast<const char*>(&lengthNL), sizeof(lengthNL));
  165. uint32_t bitfieldLengthNL = htonl((*itr)->getBitfieldLength());
  166. o.write(reinterpret_cast<const char*>(&bitfieldLengthNL),
  167. sizeof(bitfieldLengthNL));
  168. o.write(reinterpret_cast<const char*>((*itr)->getBitfield()),
  169. (*itr)->getBitfieldLength());
  170. }
  171. o.close();
  172. _logger->info(MSG_SAVED_SEGMENT_FILE);
  173. } catch(std::ios::failure const& exception) {
  174. // TODO std::ios::failure doesn't give us the reasons of failure...
  175. throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_WRITE,
  176. _filename.c_str(), strerror(errno)).str());
  177. }
  178. if(!File(filenameTemp).renameTo(_filename)) {
  179. throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_WRITE,
  180. _filename.c_str(), strerror(errno)).str());
  181. }
  182. }
  183. // It is assumed that integers are saved as:
  184. // 1) host byte order if version == 0000
  185. // 2) network byte order if version == 0001
  186. void DefaultBtProgressInfoFile::load()
  187. {
  188. _logger->info(MSG_LOADING_SEGMENT_FILE, _filename.c_str());
  189. std::ifstream in(_filename.c_str(), std::ios::in|std::ios::binary);
  190. unsigned char* savedInfoHash = 0;
  191. unsigned char* savedBitfield = 0;
  192. try {
  193. in.exceptions(std::ios::failbit);
  194. unsigned char versionBuf[2];
  195. in.read((char*)versionBuf, sizeof(versionBuf));
  196. std::string versionHex = Util::toHex(versionBuf, sizeof(versionBuf));
  197. int version;
  198. if(DefaultBtProgressInfoFile::V0000 == versionHex) {
  199. version = 0;
  200. } else if(DefaultBtProgressInfoFile::V0001 == versionHex) {
  201. version = 1;
  202. } else {
  203. throw DlAbortEx
  204. (StringFormat("Unsupported ctrl file version: %s",
  205. versionHex.c_str()).str());
  206. }
  207. unsigned char extension[4];
  208. in.read((char*)extension, sizeof(extension));
  209. bool infoHashCheckEnabled = false;
  210. if(extension[3]&1 && isTorrentDownload()) {
  211. infoHashCheckEnabled = true;
  212. _logger->debug("InfoHash checking enabled.");
  213. }
  214. uint32_t infoHashLength;
  215. in.read(reinterpret_cast<char*>(&infoHashLength), sizeof(infoHashLength));
  216. if(version >= 1) {
  217. infoHashLength = ntohl(infoHashLength);
  218. }
  219. if((infoHashLength < 0) ||
  220. ((infoHashLength == 0) && infoHashCheckEnabled)) {
  221. throw DlAbortEx
  222. (StringFormat("Invalid info hash length: %d", infoHashLength).str());
  223. }
  224. if(infoHashLength > 0) {
  225. savedInfoHash = new unsigned char[infoHashLength];
  226. in.read(reinterpret_cast<char*>(savedInfoHash), infoHashLength);
  227. BtContextHandle btContext(dynamic_pointer_cast<BtContext>(_dctx));
  228. if(infoHashCheckEnabled &&
  229. Util::toHex(savedInfoHash, infoHashLength) !=
  230. btContext->getInfoHashAsString()) {
  231. throw DlAbortEx
  232. (StringFormat("info hash mismatch. expected: %s, actual: %s",
  233. btContext->getInfoHashAsString().c_str(),
  234. Util::toHex(savedInfoHash,
  235. infoHashLength).c_str()).str());
  236. }
  237. delete [] savedInfoHash;
  238. savedInfoHash = 0;
  239. }
  240. uint32_t pieceLength;
  241. in.read(reinterpret_cast<char*>(&pieceLength), sizeof(pieceLength));
  242. if(version >= 1) {
  243. pieceLength = ntohl(pieceLength);
  244. }
  245. uint64_t totalLength;
  246. in.read(reinterpret_cast<char*>(&totalLength), sizeof(totalLength));
  247. if(version >= 1) {
  248. totalLength = ntoh64(totalLength);
  249. }
  250. if(totalLength != _dctx->getTotalLength()) {
  251. throw DlAbortEx
  252. (StringFormat("total length mismatch. expected: %s, actual: %s",
  253. Util::itos(_dctx->getTotalLength()).c_str(),
  254. Util::itos(totalLength).c_str()).str());
  255. }
  256. uint64_t uploadLength;
  257. in.read(reinterpret_cast<char*>(&uploadLength), sizeof(uploadLength));
  258. if(version >= 1) {
  259. uploadLength = ntoh64(uploadLength);
  260. }
  261. #ifdef ENABLE_BITTORRENT
  262. if(isTorrentDownload()) {
  263. _btRuntime->setUploadLengthAtStartup(uploadLength);
  264. }
  265. #endif // ENABLE_BITTORRENT
  266. // TODO implement the conversion mechanism between different piece length.
  267. uint32_t bitfieldLength;
  268. in.read(reinterpret_cast<char*>(&bitfieldLength), sizeof(bitfieldLength));
  269. if(version >= 1) {
  270. bitfieldLength = ntohl(bitfieldLength);
  271. }
  272. uint32_t expectedBitfieldLength =
  273. ((totalLength+pieceLength-1)/pieceLength+7)/8;
  274. if(expectedBitfieldLength != bitfieldLength) {
  275. throw DlAbortEx
  276. (StringFormat("bitfield length mismatch. expected: %d, actual: %d",
  277. expectedBitfieldLength,
  278. bitfieldLength).str());
  279. }
  280. savedBitfield = new unsigned char[bitfieldLength];
  281. in.read(reinterpret_cast<char*>(savedBitfield), bitfieldLength);
  282. if(pieceLength == _dctx->getPieceLength()) {
  283. _pieceStorage->setBitfield(savedBitfield, bitfieldLength);
  284. delete [] savedBitfield;
  285. savedBitfield = 0;
  286. uint32_t numInFlightPiece;
  287. in.read(reinterpret_cast<char*>(&numInFlightPiece),
  288. sizeof(numInFlightPiece));
  289. if(version >= 1) {
  290. numInFlightPiece = ntohl(numInFlightPiece);
  291. }
  292. Pieces inFlightPieces;
  293. while(numInFlightPiece--) {
  294. uint32_t index;
  295. in.read(reinterpret_cast<char*>(&index), sizeof(index));
  296. if(version >= 1) {
  297. index = ntohl(index);
  298. }
  299. if(!(index < _dctx->getNumPieces())) {
  300. throw DlAbortEx
  301. (StringFormat("piece index out of range: %u", index).str());
  302. }
  303. uint32_t length;
  304. in.read(reinterpret_cast<char*>(&length), sizeof(length));
  305. if(version >= 1) {
  306. length = ntohl(length);
  307. }
  308. if(!(length <=_dctx->getPieceLength())) {
  309. throw DlAbortEx
  310. (StringFormat("piece length out of range: %u", length).str());
  311. }
  312. PieceHandle piece(new Piece(index, length));
  313. uint32_t bitfieldLength;
  314. in.read(reinterpret_cast<char*>(&bitfieldLength),
  315. sizeof(bitfieldLength));
  316. if(version >= 1) {
  317. bitfieldLength = ntohl(bitfieldLength);
  318. }
  319. if(piece->getBitfieldLength() != bitfieldLength) {
  320. throw DlAbortEx
  321. (StringFormat("piece bitfield length mismatch."
  322. " expected: %u actual: %u",
  323. piece->getBitfieldLength(), bitfieldLength).str());
  324. }
  325. savedBitfield = new unsigned char[bitfieldLength];
  326. in.read(reinterpret_cast<char*>(savedBitfield), bitfieldLength);
  327. piece->setBitfield(savedBitfield, bitfieldLength);
  328. #ifdef ENABLE_MESSAGE_DIGEST
  329. piece->setHashAlgo(_dctx->getPieceHashAlgo());
  330. #endif // ENABLE_MESSAGE_DIGEST
  331. delete [] savedBitfield;
  332. savedBitfield = 0;
  333. inFlightPieces.push_back(piece);
  334. }
  335. _pieceStorage->addInFlightPiece(inFlightPieces);
  336. } else {
  337. uint32_t numInFlightPiece;
  338. in.read(reinterpret_cast<char*>(&numInFlightPiece),
  339. sizeof(numInFlightPiece));
  340. if(version >= 1) {
  341. numInFlightPiece = ntohl(numInFlightPiece);
  342. }
  343. BitfieldMan src(pieceLength, totalLength);
  344. src.setBitfield(savedBitfield, bitfieldLength);
  345. if((src.getCompletedLength() || numInFlightPiece) &&
  346. !_option->getAsBool(PREF_ALLOW_PIECE_LENGTH_CHANGE)) {
  347. throw DownloadFailureException
  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. }
  352. BitfieldMan dest(_dctx->getPieceLength(), totalLength);
  353. Util::convertBitfield(&dest, &src);
  354. _pieceStorage->setBitfield(dest.getBitfield(), dest.getBitfieldLength());
  355. delete [] savedBitfield;
  356. savedBitfield = 0;
  357. }
  358. _logger->info(MSG_LOADED_SEGMENT_FILE);
  359. } catch(std::ios::failure const& exception) {
  360. delete [] savedBitfield;
  361. delete [] savedInfoHash;
  362. // TODO std::ios::failure doesn't give us the reasons of failure...
  363. throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_READ,
  364. _filename.c_str(), strerror(errno)).str());
  365. }
  366. }
  367. void DefaultBtProgressInfoFile::removeFile()
  368. {
  369. if(exists()) {
  370. File f(_filename);
  371. f.remove();
  372. }
  373. }
  374. bool DefaultBtProgressInfoFile::exists()
  375. {
  376. File f(_filename);
  377. if(f.isFile()) {
  378. _logger->info(MSG_SEGMENT_FILE_EXISTS, _filename.c_str());
  379. return true;
  380. } else {
  381. _logger->info(MSG_SEGMENT_FILE_DOES_NOT_EXIST, _filename.c_str());
  382. return false;
  383. }
  384. }
  385. #ifdef ENABLE_BITTORRENT
  386. void DefaultBtProgressInfoFile::setPeerStorage
  387. (const SharedHandle<PeerStorage>& peerStorage)
  388. {
  389. _peerStorage = peerStorage;
  390. }
  391. void DefaultBtProgressInfoFile::setBtRuntime
  392. (const SharedHandle<BtRuntime>& btRuntime)
  393. {
  394. _btRuntime = btRuntime;
  395. }
  396. #endif // ENABLE_BITTORRENT
  397. } // namespace aria2