DefaultBtProgressInfoFile.cc 12 KB

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