DefaultBtProgressInfoFile.cc 14 KB

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