DefaultBtContext.cc 16 KB

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