SegmentMan.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 "SegmentMan.h"
  36. #include "DlAbortEx.h"
  37. #include "Util.h"
  38. #include "File.h"
  39. #include "message.h"
  40. #include "prefs.h"
  41. #include "LogFactory.h"
  42. #include "BitfieldManFactory.h"
  43. #ifdef ENABLE_MESSAGE_DIGEST
  44. #include "ChunkChecksumValidator.h"
  45. #endif // ENABLE_MESSAGE_DIGEST
  46. #include <sys/types.h>
  47. #include <sys/stat.h>
  48. #include <unistd.h>
  49. #include <errno.h>
  50. SegmentMan::SegmentMan():logger(LogFactory::getInstance()),
  51. bitfield(0),
  52. totalSize(0),
  53. isSplittable(true),
  54. downloadStarted(false),
  55. dir("."),
  56. errors(0),
  57. diskWriter(0)
  58. #ifdef ENABLE_MESSAGE_DIGEST
  59. ,
  60. chunkHashLength(0),
  61. digestAlgo(DIGEST_ALGO_SHA1)
  62. #endif // ENABLE_MESSAGE_DIGEST
  63. {}
  64. SegmentMan::~SegmentMan() {
  65. delete bitfield;
  66. }
  67. bool SegmentMan::segmentFileExists() const {
  68. if(!isSplittable) {
  69. return false;
  70. }
  71. string segFilename = getSegmentFilePath();
  72. File f(segFilename);
  73. if(f.isFile()) {
  74. logger->info(MSG_SEGMENT_FILE_EXISTS, segFilename.c_str());
  75. return true;
  76. } else {
  77. logger->info(MSG_SEGMENT_FILE_DOES_NOT_EXIST, segFilename.c_str());
  78. return false;
  79. }
  80. }
  81. void SegmentMan::load() {
  82. if(!isSplittable) {
  83. return;
  84. }
  85. string segFilename = getSegmentFilePath();
  86. logger->info(MSG_LOADING_SEGMENT_FILE, segFilename.c_str());
  87. FILE* segFile = openSegFile(segFilename, "r+");
  88. try {
  89. read(segFile);
  90. fclose(segFile);
  91. } catch(string ex) {
  92. fclose(segFile);
  93. throw new DlAbortEx(EX_SEGMENT_FILE_READ,
  94. segFilename.c_str(), strerror(errno));
  95. }
  96. logger->info(MSG_LOADED_SEGMENT_FILE);
  97. }
  98. void SegmentMan::save() const {
  99. if(!isSplittable || totalSize == 0) {
  100. return;
  101. }
  102. string segFilename = getSegmentFilePath();
  103. logger->info(MSG_SAVING_SEGMENT_FILE, segFilename.c_str());
  104. FILE* segFile = openSegFile(segFilename, "w");
  105. try {
  106. if(fwrite(&totalSize, sizeof(totalSize), 1, segFile) < 1) {
  107. throw string("writeError");
  108. }
  109. int segmentLength = bitfield->getBlockLength();
  110. if(fwrite(&segmentLength, sizeof(segmentLength), 1, segFile) < 1) {
  111. throw string("writeError");
  112. }
  113. if(bitfield) {
  114. int bitfieldLength = bitfield->getBitfieldLength();
  115. if(fwrite(&bitfieldLength, sizeof(bitfieldLength), 1, segFile) < 1) {
  116. throw string("writeError");
  117. }
  118. if(fwrite(bitfield->getBitfield(), bitfield->getBitfieldLength(),
  119. 1, segFile) < 1) {
  120. throw string("writeError");
  121. }
  122. } else {
  123. int i = 0;
  124. if(fwrite(&i, sizeof(i), 1, segFile) < 1) {
  125. throw string("writeError");
  126. }
  127. }
  128. int usedSegmentCount = usedSegmentEntries.size();
  129. if(fwrite(&usedSegmentCount, sizeof(usedSegmentCount), 1, segFile) < 1) {
  130. throw string("writeError");
  131. }
  132. for(SegmentEntries::const_iterator itr = usedSegmentEntries.begin();
  133. itr != usedSegmentEntries.end(); itr++) {
  134. if(fwrite((*itr)->segment.get(), sizeof(Segment), 1, segFile) < 1) {
  135. throw string("writeError");
  136. }
  137. }
  138. fclose(segFile);
  139. logger->info(MSG_SAVED_SEGMENT_FILE);
  140. } catch(string ex) {
  141. fclose(segFile);
  142. throw new DlAbortEx(EX_SEGMENT_FILE_WRITE,
  143. segFilename.c_str(), strerror(errno));
  144. }
  145. }
  146. FILE* SegmentMan::openSegFile(const string& segFilename, const string& mode) const {
  147. FILE* segFile = fopen(segFilename.c_str(), mode.c_str());
  148. if(segFile == NULL) {
  149. throw new DlAbortEx(EX_SEGMENT_FILE_OPEN,
  150. segFilename.c_str(), strerror(errno));
  151. }
  152. return segFile;
  153. }
  154. void SegmentMan::read(FILE* file) {
  155. assert(file != NULL);
  156. if(fread(&totalSize, sizeof(totalSize), 1, file) < 1) {
  157. throw string("readError");
  158. }
  159. int segmentSize;
  160. if(fread(&segmentSize, sizeof(segmentSize), 1, file) < 1) {
  161. throw string("readError");
  162. }
  163. int bitfieldLength;
  164. if(fread(&bitfieldLength, sizeof(bitfieldLength), 1, file) < 1) {
  165. throw string("readError");
  166. }
  167. if(bitfieldLength > 0) {
  168. initBitfield(segmentSize, totalSize);
  169. unsigned char* savedBitfield = new unsigned char[bitfield->getBitfieldLength()];
  170. if(fread(savedBitfield, bitfield->getBitfieldLength(), 1, file) < 1) {
  171. delete [] savedBitfield;
  172. throw string("readError");
  173. } else {
  174. bitfield->setBitfield(savedBitfield, bitfield->getBitfieldLength());
  175. delete [] savedBitfield;
  176. }
  177. }
  178. int segmentCount;
  179. if(fread(&segmentCount, sizeof(segmentCount), 1, file) < 1) {
  180. throw string("readError");
  181. }
  182. while(segmentCount--) {
  183. SegmentHandle seg;
  184. if(fread(seg.get(), sizeof(Segment), 1, file) < 1) {
  185. throw string("readError");
  186. }
  187. usedSegmentEntries.push_back(SegmentEntryHandle(new SegmentEntry(0, seg)));
  188. }
  189. }
  190. void SegmentMan::remove() const {
  191. if(!isSplittable) {
  192. return;
  193. }
  194. if(segmentFileExists()) {
  195. File f(getSegmentFilePath());
  196. f.remove();
  197. }
  198. }
  199. bool SegmentMan::finished() const {
  200. if(!downloadStarted) {
  201. return false;
  202. }
  203. if(!bitfield) {
  204. return false;
  205. }
  206. assert(bitfield);
  207. return bitfield->isAllBitSet();
  208. }
  209. void SegmentMan::removeIfFinished() const {
  210. if(finished()) {
  211. remove();
  212. }
  213. }
  214. void SegmentMan::init() {
  215. totalSize = 0;
  216. isSplittable = false;
  217. downloadStarted = false;
  218. errors = 0;
  219. //segments.clear();
  220. usedSegmentEntries.clear();
  221. delete bitfield;
  222. bitfield = 0;
  223. peerStats.clear();
  224. diskWriter->closeFile();
  225. }
  226. void SegmentMan::initBitfield(int32_t segmentLength, int64_t totalLength) {
  227. delete bitfield;
  228. this->bitfield = BitfieldManFactory::getFactoryInstance()->createBitfieldMan(segmentLength, totalLength);
  229. }
  230. SegmentHandle SegmentMan::checkoutSegment(int32_t cuid, int32_t index) {
  231. logger->debug("Attach segment#%d to CUID#%d.", index, cuid);
  232. bitfield->setUseBit(index);
  233. SegmentEntryHandle segmentEntry = getSegmentEntryByIndex(index);
  234. SegmentHandle segment(0);
  235. if(segmentEntry.isNull()) {
  236. segment = new Segment(index, bitfield->getBlockLength(index),
  237. bitfield->getBlockLength());
  238. SegmentEntryHandle entry = new SegmentEntry(cuid, segment);
  239. usedSegmentEntries.push_back(entry);
  240. } else {
  241. segmentEntry->cuid = cuid;
  242. segment = segmentEntry->segment;
  243. }
  244. logger->debug("index=%d, length=%d, segmentLength=%d, writtenLength=%d",
  245. segment->index, segment->length, segment->segmentLength,
  246. segment->writtenLength);
  247. return segment;
  248. }
  249. SegmentHandle SegmentMan::onNullBitfield(int32_t cuid) {
  250. if(usedSegmentEntries.size() == 0) {
  251. SegmentHandle segment = new Segment(0, 0, 0);
  252. usedSegmentEntries.push_back(SegmentEntryHandle(new SegmentEntry(cuid, segment)));
  253. return segment;
  254. } else {
  255. SegmentEntryHandle segmentEntry = getSegmentEntryByCuid(cuid);
  256. if(segmentEntry.isNull()) {
  257. return 0;
  258. } else {
  259. return segmentEntry->segment;
  260. }
  261. }
  262. }
  263. SegmentEntryHandle SegmentMan::findSlowerSegmentEntry(const PeerStatHandle& peerStat) const {
  264. int speed = (int)(peerStat->getAvgDownloadSpeed()*0.8);
  265. SegmentEntryHandle slowSegmentEntry(0);
  266. for(SegmentEntries::const_iterator itr = usedSegmentEntries.begin();
  267. itr != usedSegmentEntries.end(); ++itr) {
  268. const SegmentEntryHandle& segmentEntry = *itr;
  269. if(segmentEntry->cuid == 0) {
  270. continue;
  271. }
  272. PeerStatHandle p = getPeerStat(segmentEntry->cuid);
  273. if(!p.get() || p->getCuid() == peerStat->getCuid() ||
  274. p->getStatus() != PeerStat::ACTIVE ||
  275. !p->getDownloadStartTime().elapsed(option->getAsInt(PREF_STARTUP_IDLE_TIME))) {
  276. continue;
  277. }
  278. int pSpeed = p->calculateDownloadSpeed();
  279. if(pSpeed < speed) {
  280. speed = pSpeed;
  281. slowSegmentEntry = segmentEntry;
  282. }
  283. }
  284. return slowSegmentEntry;
  285. }
  286. SegmentHandle SegmentMan::getSegment(int32_t cuid) {
  287. if(!bitfield) {
  288. return onNullBitfield(cuid);
  289. }
  290. SegmentEntryHandle segmentEntry = getSegmentEntryByCuid(cuid);
  291. if(!segmentEntry.isNull()) {
  292. return segmentEntry->segment;
  293. }
  294. int index = bitfield->getSparseMissingUnusedIndex();
  295. if(index == -1) {
  296. PeerStatHandle myPeerStat = getPeerStat(cuid);
  297. if(!myPeerStat.get()) {
  298. return 0;
  299. }
  300. SegmentEntryHandle slowSegmentEntry = findSlowerSegmentEntry(myPeerStat);
  301. if(slowSegmentEntry.get()) {
  302. logger->info("CUID#%d cancels segment index=%d. CUID#%d handles it instead.",
  303. slowSegmentEntry->cuid,
  304. slowSegmentEntry->segment->index,
  305. cuid);
  306. PeerStatHandle slowPeerStat = getPeerStat(slowSegmentEntry->cuid);
  307. slowPeerStat->requestIdle();
  308. cancelSegment(slowSegmentEntry->cuid);
  309. return checkoutSegment(cuid, slowSegmentEntry->segment->index);
  310. } else {
  311. return 0;
  312. }
  313. } else {
  314. return checkoutSegment(cuid, index);
  315. }
  316. }
  317. SegmentHandle SegmentMan::getSegment(int32_t cuid, int32_t index) {
  318. if(!bitfield) {
  319. return onNullBitfield(cuid);
  320. }
  321. if(index < 0 || (int32_t)bitfield->countBlock() <= index) {
  322. return 0;
  323. }
  324. if(bitfield->isBitSet(index) || bitfield->isUseBitSet(index)) {
  325. return 0;
  326. } else {
  327. return checkoutSegment(cuid, index);
  328. }
  329. }
  330. /*
  331. bool SegmentMan::updateSegment(int cuid, const Segment& segment) {
  332. if(segment.isNull()) {
  333. return false;
  334. }
  335. SegmentEntryHandle segmentEntry = getSegmentEntryByCuid(cuid);
  336. if(segmentEntry.isNull()) {
  337. return false;
  338. } else {
  339. segmentEntry->segment = segment;
  340. return true;
  341. }
  342. }
  343. */
  344. void SegmentMan::cancelSegment(int32_t cuid) {
  345. if(bitfield) {
  346. for(SegmentEntries::iterator itr = usedSegmentEntries.begin();
  347. itr != usedSegmentEntries.end(); ++itr) {
  348. if((*itr)->cuid == cuid) {
  349. bitfield->unsetUseBit((*itr)->segment->index);
  350. (*itr)->cuid = 0;
  351. break;
  352. }
  353. }
  354. } else {
  355. usedSegmentEntries.clear();
  356. }
  357. }
  358. bool SegmentMan::completeSegment(int32_t cuid, const SegmentHandle& segment) {
  359. if(segment->isNull()) {
  360. return false;
  361. }
  362. if(bitfield) {
  363. bitfield->unsetUseBit(segment->index);
  364. bitfield->setBit(segment->index);
  365. } else {
  366. initBitfield(option->getAsInt(PREF_SEGMENT_SIZE), segment->writtenLength);
  367. bitfield->setAllBit();
  368. }
  369. SegmentEntries::iterator itr = getSegmentEntryIteratorByCuid(cuid);
  370. if(itr == usedSegmentEntries.end()) {
  371. return false;
  372. } else {
  373. usedSegmentEntries.erase(itr);
  374. return true;
  375. }
  376. }
  377. bool SegmentMan::hasSegment(int32_t index) const {
  378. if(bitfield) {
  379. return bitfield->isBitSet(index);
  380. } else {
  381. return false;
  382. }
  383. }
  384. int64_t SegmentMan::getDownloadLength() const {
  385. int64_t dlLength = 0;
  386. if(bitfield) {
  387. dlLength += bitfield->getCompletedLength();
  388. }
  389. for(SegmentEntries::const_iterator itr = usedSegmentEntries.begin();
  390. itr != usedSegmentEntries.end(); itr++) {
  391. dlLength += (*itr)->segment->writtenLength;
  392. }
  393. return dlLength;
  394. }
  395. void SegmentMan::registerPeerStat(const PeerStatHandle& peerStat) {
  396. PeerStatHandle temp = getPeerStat(peerStat->getCuid());
  397. if(!temp.get()) {
  398. peerStats.push_back(peerStat);
  399. }
  400. }
  401. int32_t SegmentMan::calculateDownloadSpeed() const {
  402. int speed = 0;
  403. for(PeerStats::const_iterator itr = peerStats.begin();
  404. itr != peerStats.end(); itr++) {
  405. const PeerStatHandle& peerStat = *itr;
  406. if(peerStat->getStatus() == PeerStat::ACTIVE) {
  407. speed += peerStat->calculateDownloadSpeed();
  408. }
  409. }
  410. return speed;
  411. }
  412. bool SegmentMan::fileExists() {
  413. return File(getFilePath()).exists();
  414. }
  415. bool SegmentMan::shouldCancelDownloadForSafety() {
  416. return fileExists() && !segmentFileExists() &&
  417. option->get(PREF_ALLOW_OVERWRITE) != V_TRUE;
  418. }
  419. void SegmentMan::markAllPiecesDone()
  420. {
  421. if(bitfield) {
  422. bitfield->setAllBit();
  423. }
  424. }
  425. #ifdef ENABLE_MESSAGE_DIGEST
  426. void SegmentMan::checkIntegrity()
  427. {
  428. logger->notice("Validating file %s",
  429. getFilePath().c_str());
  430. ChunkChecksumValidator v;
  431. v.setDigestAlgo(digestAlgo);
  432. v.setDiskWriter(diskWriter);
  433. v.setFileAllocationMonitor(FileAllocationMonitorFactory::getFactory()->createNewMonitor());
  434. v.validate(bitfield, pieceHashes, chunkHashLength);
  435. }
  436. #endif // ENABLE_MESSAGE_DIGEST
  437. #ifdef ENABLE_MESSAGE_DIGEST
  438. bool SegmentMan::isChunkChecksumValidationReady() const {
  439. return bitfield && totalSize > 0 &&
  440. ((int64_t)pieceHashes.size())*chunkHashLength >= totalSize;
  441. }
  442. #endif // ENABLE_MESSAGE_DIGEST
  443. #ifdef ENABLE_MESSAGE_DIGEST
  444. void SegmentMan::tryChunkChecksumValidation(const SegmentHandle& segment)
  445. {
  446. if(!isChunkChecksumValidationReady()) {
  447. return;
  448. }
  449. int32_t hashStartIndex;
  450. int32_t hashEndIndex;
  451. Util::indexRange(hashStartIndex, hashEndIndex,
  452. segment->getPosition(),
  453. segment->writtenLength,
  454. chunkHashLength);
  455. if(!bitfield->isBitSetOffsetRange((int64_t)hashStartIndex*chunkHashLength,
  456. chunkHashLength)) {
  457. ++hashStartIndex;
  458. }
  459. if(!bitfield->isBitSetOffsetRange((int64_t)hashEndIndex*chunkHashLength,
  460. chunkHashLength)) {
  461. --hashEndIndex;
  462. }
  463. logger->debug("hashStartIndex=%d, hashEndIndex=%d",
  464. hashStartIndex, hashEndIndex);
  465. if(hashStartIndex > hashEndIndex) {
  466. logger->debug("No chunk to verify.");
  467. return;
  468. }
  469. int64_t hashOffset = ((int64_t)hashStartIndex)*chunkHashLength;
  470. int32_t startIndex;
  471. int32_t endIndex;
  472. Util::indexRange(startIndex, endIndex,
  473. hashOffset,
  474. (hashEndIndex-hashStartIndex+1)*chunkHashLength,
  475. bitfield->getBlockLength());
  476. logger->debug("startIndex=%d, endIndex=%d", startIndex, endIndex);
  477. if(bitfield->isBitRangeSet(startIndex, endIndex)) {
  478. for(int32_t index = hashStartIndex; index <= hashEndIndex; ++index) {
  479. int64_t offset = ((int64_t)index)*chunkHashLength;
  480. int32_t dataLength =
  481. offset+chunkHashLength <= totalSize ? chunkHashLength : totalSize-offset;
  482. string actualChecksum = diskWriter->messageDigest(offset, dataLength, digestAlgo);
  483. string expectedChecksum = pieceHashes.at(index);
  484. if(expectedChecksum == actualChecksum) {
  485. logger->info("Good chunk checksum.");
  486. } else {
  487. logger->error(EX_INVALID_CHUNK_CHECKSUM,
  488. index, offset, dataLength,
  489. expectedChecksum.c_str(), actualChecksum.c_str());
  490. logger->info("Unset bit from %d to %d(inclusive)", startIndex, endIndex);
  491. bitfield->unsetBitRange(startIndex, endIndex);
  492. break;
  493. }
  494. }
  495. }
  496. }
  497. #endif // ENABLE_MESSAGE_DIGEST