DefaultBtProgressInfoFile.cc 12 KB

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