DefaultBtContext.cc 14 KB

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