DefaultBtContext.cc 15 KB

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