DefaultBtContext.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 "DefaultBtContext.h"
  36. #include "MetaFileUtil.h"
  37. #include "Dictionary.h"
  38. #include "List.h"
  39. #include "Data.h"
  40. #include "DlAbortEx.h"
  41. #include "BencodeVisitor.h"
  42. #include "Util.h"
  43. #include "MessageDigestHelper.h"
  44. #include "a2netcompat.h"
  45. #include "AnnounceTier.h"
  46. #include "SimpleRandomizer.h"
  47. #include "LogFactory.h"
  48. #include "Logger.h"
  49. #include "FileEntry.h"
  50. #include "message.h"
  51. #include "PeerMessageUtil.h"
  52. #include "StringFormat.h"
  53. #include "A2STR.h"
  54. #include <cstring>
  55. #include <ostream>
  56. #include <functional>
  57. #include <algorithm>
  58. namespace aria2 {
  59. const std::string DefaultBtContext::DEFAULT_PEER_ID_PREFIX("-aria2-");
  60. DefaultBtContext::DefaultBtContext():_peerIdPrefix(DEFAULT_PEER_ID_PREFIX),
  61. _randomizer(SimpleRandomizer::getInstance()),
  62. _ownerRequestGroup(0),
  63. _logger(LogFactory::getInstance()) {}
  64. DefaultBtContext::~DefaultBtContext() {}
  65. std::string DefaultBtContext::generatePeerId() const {
  66. std::string peerId = _peerIdPrefix;
  67. peerId += Util::randomAlpha(20-_peerIdPrefix.size(), _randomizer);
  68. if(peerId.size() > 20) {
  69. peerId.erase(20);
  70. }
  71. return peerId;
  72. }
  73. const unsigned char* DefaultBtContext::getInfoHash() const {
  74. return infoHash;
  75. }
  76. size_t DefaultBtContext::getInfoHashLength() const {
  77. return INFO_HASH_LENGTH;
  78. }
  79. const std::string& DefaultBtContext::getInfoHashAsString() const {
  80. return infoHashString;
  81. }
  82. void DefaultBtContext::clear() {
  83. memset(infoHash, 0, INFO_HASH_LENGTH);
  84. infoHashString = A2STR::NIL;
  85. pieceHashes.clear();
  86. fileEntries.clear();
  87. totalLength = 0;
  88. pieceLength = 0;
  89. fileMode = BtContext::SINGLE;
  90. numPieces = 0;
  91. name = A2STR::NIL;
  92. announceTiers.clear();
  93. _private = false;
  94. }
  95. void DefaultBtContext::extractPieceHash(const unsigned char* hashData,
  96. size_t hashDataLength,
  97. size_t hashLength) {
  98. size_t numPieces = hashDataLength/hashLength;
  99. for(size_t i = 0; i < numPieces; i++) {
  100. pieceHashes.push_back(Util::toHex(&hashData[i*hashLength],
  101. hashLength));
  102. }
  103. }
  104. void DefaultBtContext::extractFileEntries(const Dictionary* infoDic,
  105. const std::string& defaultName,
  106. const std::deque<std::string>& urlList) {
  107. const Data* nameData = dynamic_cast<const Data*>(infoDic->get(BtContext::NAME));
  108. if(nameData) {
  109. name = nameData->toString();
  110. } else {
  111. name = File(defaultName).getBasename()+".file";
  112. }
  113. const List* files = dynamic_cast<const List*>(infoDic->get(BtContext::FILES));
  114. if(files) {
  115. uint64_t length = 0;
  116. off_t offset = 0;
  117. // multi-file mode
  118. fileMode = BtContext::MULTI;
  119. const std::deque<MetaEntry*>& metaList = files->getList();
  120. for(std::deque<MetaEntry*>::const_iterator itr = metaList.begin();
  121. itr != metaList.end(); itr++) {
  122. const Dictionary* fileDic = dynamic_cast<const Dictionary*>((*itr));
  123. if(!fileDic) {
  124. continue;
  125. }
  126. const Data* lengthData =
  127. dynamic_cast<const Data*>(fileDic->get(BtContext::LENGTH));
  128. if(lengthData) {
  129. length += lengthData->toLLInt();
  130. } else {
  131. throw DlAbortEx
  132. (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file length").str());
  133. }
  134. const List* pathList =
  135. dynamic_cast<const List*>(fileDic->get(BtContext::PATH));
  136. if(!pathList) {
  137. throw DlAbortEx
  138. (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file path list").str());
  139. }
  140. const std::deque<MetaEntry*>& paths = pathList->getList();
  141. std::string path;
  142. for(size_t i = 0; i < paths.size()-1; i++) {
  143. const Data* subpath = dynamic_cast<const Data*>(paths[i]);
  144. if(subpath) {
  145. path += subpath->toString()+"/";
  146. } else {
  147. throw DlAbortEx
  148. (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file path element").str());
  149. }
  150. }
  151. const Data* lastPath = dynamic_cast<const Data*>(paths.back());
  152. if(lastPath) {
  153. path += lastPath->toString();
  154. } else {
  155. throw DlAbortEx
  156. (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file path element").str());
  157. }
  158. std::deque<std::string> uris;
  159. std::transform(urlList.begin(), urlList.end(), std::back_inserter(uris),
  160. std::bind2nd(std::plus<std::string>(), "/"+name+"/"+path));
  161. FileEntryHandle fileEntry(new FileEntry(path,
  162. lengthData->toLLInt(),
  163. offset,
  164. uris));
  165. fileEntries.push_back(fileEntry);
  166. offset += fileEntry->getLength();
  167. }
  168. totalLength = length;
  169. } else {
  170. // single-file mode;
  171. fileMode = BtContext::SINGLE;
  172. const Data* length =
  173. dynamic_cast<const Data*>(infoDic->get(BtContext::LENGTH));
  174. if(length) {
  175. totalLength = length->toLLInt();
  176. } else {
  177. throw DlAbortEx
  178. (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file length").str());
  179. }
  180. FileEntryHandle fileEntry(new FileEntry(name, totalLength, 0, urlList));
  181. fileEntries.push_back(fileEntry);
  182. }
  183. }
  184. void DefaultBtContext::extractAnnounce(const Data* announceData) {
  185. std::deque<std::string> urls;
  186. urls.push_back(Util::trim(announceData->toString()));
  187. announceTiers.push_back(AnnounceTierHandle(new AnnounceTier(urls)));
  188. }
  189. void DefaultBtContext::extractAnnounceList(const List* announceListData) {
  190. for(std::deque<MetaEntry*>::const_iterator itr = announceListData->getList().begin();
  191. itr != announceListData->getList().end(); itr++) {
  192. const List* elem = dynamic_cast<const List*>(*itr);
  193. if(!elem) {
  194. continue;
  195. }
  196. std::deque<std::string> urls;
  197. for(std::deque<MetaEntry*>::const_iterator elemItr = elem->getList().begin();
  198. elemItr != elem->getList().end(); elemItr++) {
  199. const Data* data = dynamic_cast<const Data*>(*elemItr);
  200. if(data) {
  201. urls.push_back(Util::trim(data->toString()));
  202. }
  203. }
  204. if(urls.size()) {
  205. AnnounceTierHandle tier(new AnnounceTier(urls));
  206. announceTiers.push_back(tier);
  207. }
  208. }
  209. }
  210. void DefaultBtContext::extractUrlList(std::deque<std::string>& uris,
  211. const MetaEntry* obj)
  212. {
  213. if(dynamic_cast<const List*>(obj)) {
  214. const List* urlList = reinterpret_cast<const List*>(obj);
  215. for(std::deque<MetaEntry*>::const_iterator itr = urlList->getList().begin();
  216. itr != urlList->getList().end(); ++itr) {
  217. const Data* data = dynamic_cast<const Data*>(*itr);
  218. if(data) {
  219. uris.push_back(data->toString());
  220. }
  221. }
  222. } else if(dynamic_cast<const Data*>(obj)) {
  223. const Data* urlData = reinterpret_cast<const Data*>(obj);
  224. uris.push_back(urlData->toString());
  225. }
  226. }
  227. void DefaultBtContext::extractNodes(const List* nodes)
  228. {
  229. for(std::deque<MetaEntry*>::const_iterator i = nodes->getList().begin();
  230. i != nodes->getList().end(); ++i) {
  231. const List* addrPair = dynamic_cast<const List*>(*i);
  232. if(!addrPair || addrPair->getList().size() != 2) {
  233. continue;
  234. }
  235. const Data* hostname = dynamic_cast<const Data*>(addrPair->getList()[0]);
  236. if(!hostname) {
  237. continue;
  238. }
  239. std::string h = hostname->toString();
  240. if(Util::trim(h).empty()) {
  241. continue;
  242. }
  243. const Data* port = dynamic_cast<const Data*>(addrPair->getList()[1]);
  244. if(!port) {
  245. continue;
  246. }
  247. uint16_t p = port->toInt();
  248. if(p == 0) {
  249. continue;
  250. }
  251. _nodes.push_back(std::pair<std::string, uint16_t>(h, p));
  252. }
  253. }
  254. void DefaultBtContext::loadFromMemory(const unsigned char* content,
  255. size_t length,
  256. const std::string& defaultName)
  257. {
  258. SharedHandle<MetaEntry> rootEntry(MetaFileUtil::bdecoding(content, length));
  259. const Dictionary* rootDic = dynamic_cast<const Dictionary*>(rootEntry.get());
  260. if(!rootDic) {
  261. throw DlAbortEx
  262. (StringFormat("torrent file does not contain a root dictionary .").str());
  263. }
  264. processRootDictionary(rootDic, defaultName);
  265. }
  266. void DefaultBtContext::load(const std::string& torrentFile) {
  267. SharedHandle<MetaEntry> rootEntry(MetaFileUtil::parseMetaFile(torrentFile));
  268. const Dictionary* rootDic = dynamic_cast<const Dictionary*>(rootEntry.get());
  269. if(!rootDic) {
  270. throw DlAbortEx
  271. (StringFormat("torrent file does not contain a root dictionary .").str());
  272. }
  273. processRootDictionary(rootDic, torrentFile);
  274. }
  275. void DefaultBtContext::processRootDictionary(const Dictionary* rootDic, const std::string& defaultName)
  276. {
  277. clear();
  278. const Dictionary* infoDic =
  279. dynamic_cast<const Dictionary*>(rootDic->get(BtContext::INFO));
  280. if(!infoDic) {
  281. throw DlAbortEx
  282. (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "info directory").str());
  283. }
  284. // retrieve infoHash
  285. BencodeVisitor v;
  286. infoDic->accept(&v);
  287. MessageDigestHelper::digest(infoHash, INFO_HASH_LENGTH,
  288. MessageDigestContext::SHA1,
  289. v.getBencodedData().c_str(),
  290. v.getBencodedData().size());
  291. infoHashString = Util::toHex(infoHash, INFO_HASH_LENGTH);
  292. // calculate the number of pieces
  293. const Data* pieceHashData =
  294. dynamic_cast<const Data*>(infoDic->get(BtContext::PIECES));
  295. if(!pieceHashData) {
  296. throw DlAbortEx
  297. (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "pieces").str());
  298. }
  299. if(pieceHashData->getLen() == 0) {
  300. throw DlAbortEx("The length of piece hash is 0.");
  301. }
  302. numPieces = pieceHashData->getLen()/PIECE_HASH_LENGTH;
  303. if(numPieces == 0) {
  304. throw DlAbortEx("The number of pieces is 0.");
  305. }
  306. // retrieve piece length
  307. const Data* pieceLengthData =
  308. dynamic_cast<const Data*>(infoDic->get(BtContext::PIECE_LENGTH));
  309. if(!pieceLengthData) {
  310. throw DlAbortEx
  311. (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "piece length").str());
  312. }
  313. pieceLength = pieceLengthData->toInt();
  314. // retrieve piece hashes
  315. extractPieceHash(pieceHashData->getData(), pieceHashData->getLen(),
  316. PIECE_HASH_LENGTH);
  317. const Data* privateFlag =
  318. dynamic_cast<const Data*>(infoDic->get(BtContext::PRIVATE));
  319. if(privateFlag) {
  320. if(privateFlag->toString() == BtContext::PRIVATE_ON) {
  321. _private = true;
  322. }
  323. }
  324. // retrieve uri-list.
  325. // This implemantation obeys HTTP-Seeding specification:
  326. // see http://www.getright.com/seedtorrent.html
  327. std::deque<std::string> urlList;
  328. extractUrlList(urlList, rootDic->get(BtContext::URL_LIST));
  329. // retrieve file entries
  330. extractFileEntries(infoDic, defaultName, urlList);
  331. if((totalLength+pieceLength-1)/pieceLength != numPieces) {
  332. throw DlAbortEx("Too few/many piece hash.");
  333. }
  334. // retrieve announce
  335. const Data* announceData =
  336. dynamic_cast<const Data*>(rootDic->get(BtContext::ANNOUNCE));
  337. const List* announceListData =
  338. dynamic_cast<const List*>(rootDic->get(BtContext::ANNOUNCE_LIST));
  339. if(announceListData) {
  340. extractAnnounceList(announceListData);
  341. } else if(announceData) {
  342. extractAnnounce(announceData);
  343. }
  344. // retrieve nodes
  345. const List* nodes =
  346. dynamic_cast<const List*>(rootDic->get(BtContext::NODES));
  347. if(nodes) {
  348. extractNodes(nodes);
  349. }
  350. }
  351. const std::string& DefaultBtContext::getPieceHash(size_t index) const {
  352. if(index < numPieces) {
  353. return pieceHashes[index];
  354. } else {
  355. return A2STR::NIL;
  356. }
  357. }
  358. uint64_t DefaultBtContext::getTotalLength() const {
  359. return totalLength;
  360. }
  361. BtContext::FILE_MODE DefaultBtContext::getFileMode() const {
  362. return fileMode;
  363. }
  364. FileEntries DefaultBtContext::getFileEntries() const {
  365. return fileEntries;
  366. }
  367. const std::string& DefaultBtContext::getPieceHashAlgo() const
  368. {
  369. return MessageDigestContext::SHA1;
  370. }
  371. AnnounceTiers DefaultBtContext::getAnnounceTiers() const {
  372. return announceTiers;
  373. }
  374. const std::string& DefaultBtContext::getName() const {
  375. return name;
  376. }
  377. size_t DefaultBtContext::getPieceLength() const {
  378. return pieceLength;
  379. }
  380. size_t DefaultBtContext::getNumPieces() const {
  381. return numPieces;
  382. }
  383. std::string DefaultBtContext::getActualBasePath() const
  384. {
  385. return _dir+"/"+name;
  386. }
  387. void DefaultBtContext::computeFastSet
  388. (std::deque<size_t>& fastSet, const std::string& ipaddr, size_t fastSetSize)
  389. {
  390. unsigned char compact[6];
  391. if(!PeerMessageUtil::createcompact(compact, ipaddr, 0)) {
  392. return;
  393. }
  394. unsigned char tx[24];
  395. memcpy(tx, compact, 4);
  396. if((tx[0] & 0x80) == 0 || (tx[0] & 0x40) == 0) {
  397. tx[2] = 0x00;
  398. tx[3] = 0x00;
  399. } else {
  400. tx[3] = 0x00;
  401. }
  402. memcpy(tx+4, infoHash, 20);
  403. unsigned char x[20];
  404. MessageDigestHelper::digest(x, sizeof(x), MessageDigestContext::SHA1, tx, 24);
  405. while(fastSet.size() < fastSetSize) {
  406. for(size_t i = 0; i < 5 && fastSet.size() < fastSetSize; i++) {
  407. size_t j = i*4;
  408. uint32_t ny;
  409. memcpy(&ny, x+j, 4);
  410. uint32_t y = ntohl(ny);
  411. size_t index = y%numPieces;
  412. if(std::find(fastSet.begin(), fastSet.end(), index) == fastSet.end()) {
  413. fastSet.push_back(index);
  414. }
  415. }
  416. unsigned char temp[20];
  417. MessageDigestHelper::digest(temp, sizeof(temp), MessageDigestContext::SHA1, x, sizeof(x));
  418. memcpy(x, temp, sizeof(x));
  419. }
  420. }
  421. std::ostream& operator<<(std::ostream& o, const DefaultBtContext& ctx)
  422. {
  423. o << "*** BitTorrent File Information ***" << "\n";
  424. o << "Mode: " << (ctx.getFileMode() == DownloadContext::SINGLE ? "Single File Torrent":"Multi File Torrent") << "\n";
  425. o << "Announce:" << "\n";
  426. AnnounceTiers tiers = ctx.getAnnounceTiers();
  427. for(AnnounceTiers::const_iterator itr = tiers.begin(); itr != tiers.end(); ++itr) {
  428. const AnnounceTierHandle& tier = *itr;
  429. for(std::deque<std::string>::const_iterator uriItr = tier->urls.begin(); uriItr != tier->urls.end(); ++uriItr) {
  430. o << " " << *uriItr;
  431. }
  432. o << "\n";
  433. }
  434. o << "Info Hash: " << ctx.getInfoHashAsString() << "\n";
  435. o << "Piece Length: " << Util::abbrevSize(ctx.getPieceLength()) << "B\n";
  436. o << "The Number of Pieces: " << ctx.getNumPieces() << "\n";
  437. o << "Total Length: " << Util::abbrevSize(ctx.getTotalLength()) << "B\n";
  438. if(ctx.getFileMode() == DownloadContext::MULTI) {
  439. o << "Name: " << ctx.getName() << "\n";
  440. }
  441. Util::toStream(o, ctx.getFileEntries());
  442. return o;
  443. }
  444. void DefaultBtContext::setRandomizer(const RandomizerHandle& randomizer)
  445. {
  446. _randomizer = randomizer;
  447. }
  448. std::deque<std::pair<std::string, uint16_t> >&
  449. DefaultBtContext::getNodes()
  450. {
  451. return _nodes;
  452. }
  453. void DefaultBtContext::setInfoHash(const unsigned char* infoHash)
  454. {
  455. memcpy(this->infoHash, infoHash, sizeof(this->infoHash));
  456. }
  457. } // namespace aria2