DefaultBtProgressInfoFile.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 "BtContext.h"
  37. #include "PieceStorage.h"
  38. #include "Piece.h"
  39. #include "PeerStorage.h"
  40. #include "BtRuntime.h"
  41. #include "BitfieldMan.h"
  42. #include "Option.h"
  43. #include "TransferStat.h"
  44. #include "BtRegistry.h"
  45. #include "LogFactory.h"
  46. #include "Logger.h"
  47. #include "prefs.h"
  48. #include "DlAbortEx.h"
  49. #include "message.h"
  50. #include "File.h"
  51. #include "Util.h"
  52. #include "a2io.h"
  53. #include "DownloadFailureException.h"
  54. #include "StringFormat.h"
  55. #include <fstream>
  56. #include <cerrno>
  57. #include <cstring>
  58. namespace aria2 {
  59. const std::string DefaultBtProgressInfoFile::V0000("0000");
  60. static std::string createFilename(const SharedHandle<DownloadContext>& dctx)
  61. {
  62. return dctx->getActualBasePath()+".aria2";
  63. }
  64. DefaultBtProgressInfoFile::DefaultBtProgressInfoFile(const DownloadContextHandle& dctx,
  65. const PieceStorageHandle& pieceStorage,
  66. const Option* option):
  67. _dctx(dctx),
  68. _pieceStorage(pieceStorage),
  69. _option(option),
  70. _logger(LogFactory::getInstance()),
  71. _filename(createFilename(_dctx))
  72. {}
  73. DefaultBtProgressInfoFile::~DefaultBtProgressInfoFile() {}
  74. void DefaultBtProgressInfoFile::updateFilename()
  75. {
  76. _filename = createFilename(_dctx);
  77. }
  78. bool DefaultBtProgressInfoFile::isTorrentDownload()
  79. {
  80. return !dynamic_pointer_cast<BtContext>(_dctx).isNull();
  81. }
  82. void DefaultBtProgressInfoFile::save() {
  83. _logger->info(MSG_SAVING_SEGMENT_FILE, _filename.c_str());
  84. std::string filenameTemp = _filename+"__temp";
  85. std::ofstream o(filenameTemp.c_str(), std::ios::out|std::ios::binary);
  86. o.exceptions(std::ios::failbit);
  87. try {
  88. bool torrentDownload = isTorrentDownload();
  89. // file version: 16 bits
  90. // value: '0'
  91. uint16_t version = 0;
  92. o.write(reinterpret_cast<const char*>(&version), sizeof(version));
  93. // extension: 32 bits
  94. // If this is BitTorrent download, then 0x00000001
  95. // Otherwise, 0x00000000
  96. char extension[4];
  97. memset(extension, 0, sizeof(extension));
  98. if(torrentDownload) {
  99. extension[3] = 1;
  100. }
  101. o.write(reinterpret_cast<const char*>(&extension), sizeof(extension));
  102. if(torrentDownload) {
  103. // infoHashLength:
  104. // length: 32 bits
  105. BtContextHandle btContext(dynamic_pointer_cast<BtContext>(_dctx));
  106. uint32_t infoHashLength = btContext->getInfoHashLength();
  107. o.write(reinterpret_cast<const char*>(&infoHashLength), sizeof(infoHashLength));
  108. // infoHash:
  109. o.write(reinterpret_cast<const char*>(btContext->getInfoHash()),
  110. btContext->getInfoHashLength());
  111. } else {
  112. // infoHashLength:
  113. // length: 32 bits
  114. uint32_t infoHashLength = 0;
  115. o.write(reinterpret_cast<const char*>(&infoHashLength), sizeof(infoHashLength));
  116. }
  117. // pieceLength: 32 bits
  118. uint32_t pieceLength = _dctx->getPieceLength();
  119. o.write(reinterpret_cast<const char*>(&pieceLength), sizeof(pieceLength));
  120. // totalLength: 64 bits
  121. uint64_t totalLength = _dctx->getTotalLength();
  122. o.write(reinterpret_cast<const char*>(&totalLength), sizeof(totalLength));
  123. // uploadLength: 64 bits
  124. uint64_t uploadLength = 0;
  125. if(torrentDownload) {
  126. BtContextHandle btContext(dynamic_pointer_cast<BtContext>(_dctx));
  127. TransferStat stat = PEER_STORAGE(btContext)->calculateStat();
  128. uploadLength = stat.getAllTimeUploadLength();
  129. }
  130. o.write(reinterpret_cast<const char*>(&uploadLength), sizeof(uploadLength));
  131. // bitfieldLength: 32 bits
  132. uint32_t bitfieldLength = _pieceStorage->getBitfieldLength();
  133. o.write(reinterpret_cast<const char*>(&bitfieldLength), sizeof(bitfieldLength));
  134. // bitfield
  135. o.write(reinterpret_cast<const char*>(_pieceStorage->getBitfield()), _pieceStorage->getBitfieldLength());
  136. // the number of in-flight piece: 32 bits
  137. // TODO implement this
  138. uint32_t numInFlightPiece = _pieceStorage->countInFlightPiece();
  139. o.write(reinterpret_cast<const char*>(&numInFlightPiece), sizeof(numInFlightPiece));
  140. Pieces inFlightPieces;
  141. _pieceStorage->getInFlightPieces(inFlightPieces);
  142. for(Pieces::const_iterator itr = inFlightPieces.begin();
  143. itr != inFlightPieces.end(); ++itr) {
  144. uint32_t index = (*itr)->getIndex();
  145. o.write(reinterpret_cast<const char*>(&index), sizeof(index));
  146. uint32_t length = (*itr)->getLength();
  147. o.write(reinterpret_cast<const char*>(&length), sizeof(length));
  148. uint32_t bitfieldLength = (*itr)->getBitfieldLength();
  149. o.write(reinterpret_cast<const char*>(&bitfieldLength), sizeof(bitfieldLength));
  150. o.write(reinterpret_cast<const char*>((*itr)->getBitfield()), bitfieldLength);
  151. }
  152. o.close();
  153. _logger->info(MSG_SAVED_SEGMENT_FILE);
  154. } catch(std::ios::failure const& exception) {
  155. // TODO std::ios::failure doesn't give us the reasons of failure...
  156. throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_WRITE,
  157. _filename.c_str(), strerror(errno)).str());
  158. }
  159. if(!File(filenameTemp).renameTo(_filename)) {
  160. throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_WRITE,
  161. _filename.c_str(), strerror(errno)).str());
  162. }
  163. }
  164. void DefaultBtProgressInfoFile::load()
  165. {
  166. _logger->info(MSG_LOADING_SEGMENT_FILE, _filename.c_str());
  167. std::ifstream in(_filename.c_str(), std::ios::in|std::ios::binary);
  168. in.exceptions(std::ios::failbit);
  169. unsigned char* savedInfoHash = 0;
  170. unsigned char* savedBitfield = 0;
  171. try {
  172. unsigned char version[2];
  173. in.read((char*)version, sizeof(version));
  174. if(DefaultBtProgressInfoFile::V0000 != Util::toHex(version, sizeof(version))) {
  175. throw DlAbortEx
  176. (StringFormat("Unsupported ctrl file version: %s",
  177. Util::toHex(version, sizeof(version)).c_str()).str());
  178. }
  179. unsigned char extension[4];
  180. in.read((char*)extension, sizeof(extension));
  181. bool infoHashCheckEnabled = false;
  182. if(extension[3]&1 && isTorrentDownload()) {
  183. infoHashCheckEnabled = true;
  184. _logger->debug("InfoHash checking enabled.");
  185. }
  186. uint32_t infoHashLength;
  187. in.read(reinterpret_cast<char*>(&infoHashLength), sizeof(infoHashLength));
  188. if((infoHashLength < 0) || ((infoHashLength == 0) && infoHashCheckEnabled)) {
  189. throw DlAbortEx
  190. (StringFormat("Invalid info hash length: %d", infoHashLength).str());
  191. }
  192. if(infoHashLength > 0) {
  193. savedInfoHash = new unsigned char[infoHashLength];
  194. in.read(reinterpret_cast<char*>(savedInfoHash), infoHashLength);
  195. BtContextHandle btContext(dynamic_pointer_cast<BtContext>(_dctx));
  196. if(infoHashCheckEnabled &&
  197. Util::toHex(savedInfoHash, infoHashLength) != btContext->getInfoHashAsString()) {
  198. throw DlAbortEx
  199. (StringFormat("info hash mismatch. expected: %s, actual: %s",
  200. btContext->getInfoHashAsString().c_str(),
  201. Util::toHex(savedInfoHash, infoHashLength).c_str()).str());
  202. }
  203. delete [] savedInfoHash;
  204. savedInfoHash = 0;
  205. }
  206. uint32_t pieceLength;
  207. in.read(reinterpret_cast<char*>(&pieceLength), sizeof(pieceLength));
  208. uint64_t totalLength;
  209. in.read(reinterpret_cast<char*>(&totalLength), sizeof(totalLength));
  210. if(totalLength != _dctx->getTotalLength()) {
  211. throw DlAbortEx
  212. (StringFormat("total length mismatch. expected: %s, actual: %s",
  213. Util::itos(_dctx->getTotalLength()).c_str(),
  214. Util::itos(totalLength).c_str()).str());
  215. }
  216. uint64_t uploadLength;
  217. in.read(reinterpret_cast<char*>(&uploadLength), sizeof(uploadLength));
  218. if(isTorrentDownload()) {
  219. BT_RUNTIME(dynamic_pointer_cast<BtContext>(_dctx))->setUploadLengthAtStartup(uploadLength);
  220. }
  221. // TODO implement the conversion mechanism between different piece length.
  222. uint32_t bitfieldLength;
  223. in.read(reinterpret_cast<char*>(&bitfieldLength), sizeof(bitfieldLength));
  224. uint32_t expectedBitfieldLength = ((totalLength+pieceLength-1)/pieceLength+7)/8;
  225. if(expectedBitfieldLength != bitfieldLength) {
  226. throw DlAbortEx
  227. (StringFormat("bitfield length mismatch. expected: %d, actual: %d",
  228. expectedBitfieldLength,
  229. bitfieldLength).str());
  230. }
  231. savedBitfield = new unsigned char[bitfieldLength];
  232. in.read(reinterpret_cast<char*>(savedBitfield), bitfieldLength);
  233. if(pieceLength == _dctx->getPieceLength()) {
  234. _pieceStorage->setBitfield(savedBitfield, bitfieldLength);
  235. delete [] savedBitfield;
  236. savedBitfield = 0;
  237. uint32_t numInFlightPiece;
  238. in.read(reinterpret_cast<char*>(&numInFlightPiece), sizeof(numInFlightPiece));
  239. Pieces inFlightPieces;
  240. while(numInFlightPiece--) {
  241. uint32_t index;
  242. in.read(reinterpret_cast<char*>(&index), sizeof(index));
  243. if(!(index < _dctx->getNumPieces())) {
  244. throw DlAbortEx
  245. (StringFormat("piece index out of range: %u", index).str());
  246. }
  247. uint32_t length;
  248. in.read(reinterpret_cast<char*>(&length), sizeof(length));
  249. if(!(length <=_dctx->getPieceLength())) {
  250. throw DlAbortEx
  251. (StringFormat("piece length out of range: %u", length).str());
  252. }
  253. PieceHandle piece(new Piece(index, length));
  254. uint32_t bitfieldLength;
  255. in.read(reinterpret_cast<char*>(&bitfieldLength), sizeof(bitfieldLength));
  256. if(piece->getBitfieldLength() != bitfieldLength) {
  257. throw DlAbortEx
  258. (StringFormat("piece bitfield length mismatch. expected: %u actual: %u",
  259. piece->getBitfieldLength(), bitfieldLength).str());
  260. }
  261. savedBitfield = new unsigned char[bitfieldLength];
  262. in.read(reinterpret_cast<char*>(savedBitfield), bitfieldLength);
  263. piece->setBitfield(savedBitfield, bitfieldLength);
  264. #ifdef ENABLE_MESSAGE_DIGEST
  265. piece->setHashAlgo(_dctx->getPieceHashAlgo());
  266. #endif // ENABLE_MESSAGE_DIGEST
  267. delete [] savedBitfield;
  268. savedBitfield = 0;
  269. inFlightPieces.push_back(piece);
  270. }
  271. _pieceStorage->addInFlightPiece(inFlightPieces);
  272. } else {
  273. uint32_t numInFlightPiece;
  274. in.read(reinterpret_cast<char*>(&numInFlightPiece), sizeof(numInFlightPiece));
  275. BitfieldMan src(pieceLength, totalLength);
  276. src.setBitfield(savedBitfield, bitfieldLength);
  277. if((src.getCompletedLength() || numInFlightPiece) &&
  278. !_option->getAsBool(PREF_ALLOW_PIECE_LENGTH_CHANGE)) {
  279. throw DownloadFailureException
  280. ("WARNING: Detected a change in piece length. You can proceed with --allow-piece-length-change=true, but you may lose some download progress.");
  281. }
  282. BitfieldMan dest(_dctx->getPieceLength(), totalLength);
  283. Util::convertBitfield(&dest, &src);
  284. _pieceStorage->setBitfield(dest.getBitfield(), dest.getBitfieldLength());
  285. delete [] savedBitfield;
  286. savedBitfield = 0;
  287. }
  288. _logger->info(MSG_LOADED_SEGMENT_FILE);
  289. } catch(std::ios::failure const& exception) {
  290. delete [] savedBitfield;
  291. delete [] savedInfoHash;
  292. // TODO std::ios::failure doesn't give us the reasons of failure...
  293. throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_READ,
  294. _filename.c_str(), strerror(errno)).str());
  295. }
  296. }
  297. void DefaultBtProgressInfoFile::removeFile() {
  298. if(exists()) {
  299. File f(_filename);
  300. f.remove();
  301. }
  302. }
  303. bool DefaultBtProgressInfoFile::exists() {
  304. File f(_filename);
  305. if(f.isFile()) {
  306. _logger->info(MSG_SEGMENT_FILE_EXISTS, _filename.c_str());
  307. return true;
  308. } else {
  309. _logger->info(MSG_SEGMENT_FILE_DOES_NOT_EXIST, _filename.c_str());
  310. return false;
  311. }
  312. }
  313. } // namespace aria2