DefaultBtProgressInfoFile.cc 14 KB

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