DefaultBtContext.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 <cassert>
  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. assert(hashDataLength > 0);
  96. assert(hashLength > 0);
  97. int32_t numPieces = hashDataLength/hashLength;
  98. assert(numPieces > 0);
  99. for(int32_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("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("files"));
  114. if(files) {
  115. int64_t length = 0;
  116. int64_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 = dynamic_cast<const Data*>(fileDic->get("length"));
  127. if(lengthData) {
  128. length += lengthData->toLLInt();
  129. } else {
  130. throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file length");
  131. }
  132. const List* pathList = dynamic_cast<const List*>(fileDic->get("path"));
  133. if(!pathList) {
  134. throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file path list");
  135. }
  136. const std::deque<MetaEntry*>& paths = pathList->getList();
  137. std::string path;
  138. for(int32_t i = 0; i < (int32_t)paths.size()-1; i++) {
  139. const Data* subpath = dynamic_cast<const Data*>(paths[i]);
  140. if(subpath) {
  141. path += subpath->toString()+"/";
  142. } else {
  143. throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file path element");
  144. }
  145. }
  146. const Data* lastPath = dynamic_cast<const Data*>(paths.back());
  147. if(lastPath) {
  148. path += lastPath->toString();
  149. } else {
  150. throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file path element");
  151. }
  152. std::deque<std::string> uris;
  153. std::transform(urlList.begin(), urlList.end(), std::back_inserter(uris),
  154. std::bind2nd(std::plus<std::string>(), "/"+name+"/"+path));
  155. FileEntryHandle fileEntry(new FileEntry(path,
  156. lengthData->toLLInt(),
  157. offset,
  158. uris));
  159. fileEntries.push_back(fileEntry);
  160. offset += fileEntry->getLength();
  161. }
  162. totalLength = length;
  163. } else {
  164. // single-file mode;
  165. fileMode = BtContext::SINGLE;
  166. const Data* length = dynamic_cast<const Data*>(infoDic->get("length"));
  167. if(length) {
  168. totalLength = length->toLLInt();
  169. } else {
  170. throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file length");
  171. }
  172. FileEntryHandle fileEntry(new FileEntry(name, totalLength, 0, urlList));
  173. fileEntries.push_back(fileEntry);
  174. }
  175. }
  176. void DefaultBtContext::extractAnnounce(const Data* announceData) {
  177. std::deque<std::string> urls;
  178. urls.push_back(Util::trim(announceData->toString()));
  179. announceTiers.push_back(AnnounceTierHandle(new AnnounceTier(urls)));
  180. }
  181. void DefaultBtContext::extractAnnounceList(const List* announceListData) {
  182. for(std::deque<MetaEntry*>::const_iterator itr = announceListData->getList().begin();
  183. itr != announceListData->getList().end(); itr++) {
  184. const List* elem = dynamic_cast<const List*>(*itr);
  185. if(!elem) {
  186. continue;
  187. }
  188. std::deque<std::string> urls;
  189. for(std::deque<MetaEntry*>::const_iterator elemItr = elem->getList().begin();
  190. elemItr != elem->getList().end(); elemItr++) {
  191. const Data* data = dynamic_cast<const Data*>(*elemItr);
  192. if(data) {
  193. urls.push_back(Util::trim(data->toString()));
  194. }
  195. }
  196. if(urls.size()) {
  197. AnnounceTierHandle tier(new AnnounceTier(urls));
  198. announceTiers.push_back(tier);
  199. }
  200. }
  201. }
  202. std::deque<std::string> DefaultBtContext::extractUrlList(const MetaEntry* obj)
  203. {
  204. std::deque<std::string> uris;
  205. if(dynamic_cast<const List*>(obj)) {
  206. const List* urlList = reinterpret_cast<const List*>(obj);
  207. for(std::deque<MetaEntry*>::const_iterator itr = urlList->getList().begin();
  208. itr != urlList->getList().end(); ++itr) {
  209. const Data* data = dynamic_cast<const Data*>(*itr);
  210. if(data) {
  211. uris.push_back(data->toString());
  212. }
  213. }
  214. } else if(dynamic_cast<const Data*>(obj)) {
  215. const Data* urlData = reinterpret_cast<const Data*>(obj);
  216. uris.push_back(urlData->toString());
  217. }
  218. return uris;
  219. }
  220. void DefaultBtContext::loadFromMemory(const char* content, int32_t length, const std::string& defaultName)
  221. {
  222. SharedHandle<MetaEntry> rootEntry = MetaFileUtil::bdecoding(content, length);
  223. const Dictionary* rootDic = dynamic_cast<const Dictionary*>(rootEntry.get());
  224. if(!rootDic) {
  225. throw new DlAbortEx("torrent file does not contain a root dictionary .");
  226. }
  227. processRootDictionary(rootDic, defaultName);
  228. }
  229. void DefaultBtContext::load(const std::string& torrentFile) {
  230. SharedHandle<MetaEntry> rootEntry = MetaFileUtil::parseMetaFile(torrentFile);
  231. const Dictionary* rootDic = dynamic_cast<const Dictionary*>(rootEntry.get());
  232. if(!rootDic) {
  233. throw new DlAbortEx("torrent file does not contain a root dictionary .");
  234. }
  235. processRootDictionary(rootDic, torrentFile);
  236. }
  237. void DefaultBtContext::processRootDictionary(const Dictionary* rootDic, const std::string& defaultName)
  238. {
  239. clear();
  240. const Dictionary* infoDic = dynamic_cast<const Dictionary*>(rootDic->get("info"));
  241. if(!infoDic) {
  242. throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "info directory");
  243. }
  244. // retrieve infoHash
  245. BencodeVisitor v;
  246. infoDic->accept(&v);
  247. MessageDigestHelper::digest(infoHash, INFO_HASH_LENGTH, "sha1",
  248. v.getBencodedData().c_str(),
  249. v.getBencodedData().size());
  250. infoHashString = Util::toHex(infoHash, INFO_HASH_LENGTH);
  251. // calculate the number of pieces
  252. const Data* pieceHashData = dynamic_cast<const Data*>(infoDic->get("pieces"));
  253. if(!pieceHashData) {
  254. throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "pieces");
  255. }
  256. numPieces = pieceHashData->getLen()/PIECE_HASH_LENGTH;
  257. // retrieve piece length
  258. const Data* pieceLengthData = dynamic_cast<const Data*>(infoDic->get("piece length"));
  259. if(!pieceLengthData) {
  260. throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "piece length");
  261. }
  262. pieceLength = pieceLengthData->toInt();
  263. // retrieve piece hashes
  264. extractPieceHash((unsigned char*)pieceHashData->getData(),
  265. pieceHashData->getLen(),
  266. PIECE_HASH_LENGTH);
  267. const Data* privateFlag = dynamic_cast<const Data*>(infoDic->get("private"));
  268. if(privateFlag) {
  269. if(privateFlag->toString() == "1") {
  270. _private = true;
  271. }
  272. }
  273. // retrieve uri-list.
  274. // This implemantation obeys HTTP-Seeding specification:
  275. // see http://www.getright.com/seedtorrent.html
  276. std::deque<std::string> urlList = extractUrlList(rootDic->get("url-list"));
  277. // retrieve file entries
  278. extractFileEntries(infoDic, defaultName, urlList);
  279. if((totalLength+pieceLength-1)/pieceLength != numPieces) {
  280. throw new DlAbortEx("Too few/many piece hash.");
  281. }
  282. // retrieve announce
  283. const Data* announceData = dynamic_cast<const Data*>(rootDic->get("announce"));
  284. const List* announceListData = dynamic_cast<const List*>(rootDic->get("announce-list"));
  285. if(announceListData) {
  286. extractAnnounceList(announceListData);
  287. } else if(announceData) {
  288. extractAnnounce(announceData);
  289. }
  290. if(!announceTiers.size()) {
  291. throw new DlAbortEx("No announce URL found.");
  292. }
  293. }
  294. std::string DefaultBtContext::getPieceHash(int32_t index) const {
  295. if(index < 0 || numPieces <= index) {
  296. return "";
  297. }
  298. return pieceHashes[index];
  299. }
  300. int64_t DefaultBtContext::getTotalLength() const {
  301. return totalLength;
  302. }
  303. BtContext::FILE_MODE DefaultBtContext::getFileMode() const {
  304. return fileMode;
  305. }
  306. FileEntries DefaultBtContext::getFileEntries() const {
  307. return fileEntries;
  308. }
  309. AnnounceTiers DefaultBtContext::getAnnounceTiers() const {
  310. return announceTiers;
  311. }
  312. std::string DefaultBtContext::getName() const {
  313. return name;
  314. }
  315. int32_t DefaultBtContext::getPieceLength() const {
  316. return pieceLength;
  317. }
  318. int32_t DefaultBtContext::getNumPieces() const {
  319. return numPieces;
  320. }
  321. std::string DefaultBtContext::getActualBasePath() const
  322. {
  323. return _dir+"/"+name;
  324. }
  325. std::deque<int32_t> DefaultBtContext::computeFastSet(const std::string& ipaddr, int32_t fastSetSize)
  326. {
  327. std::deque<int32_t> fastSet;
  328. struct in_addr saddr;
  329. if(inet_aton(ipaddr.c_str(), &saddr) == 0) {
  330. abort();
  331. }
  332. unsigned char tx[24];
  333. memcpy(tx, (void*)&saddr.s_addr, 4);
  334. if((tx[0] & 0x80) == 0 || (tx[0] & 0x40) == 0) {
  335. tx[2] = 0x00;
  336. tx[3] = 0x00;
  337. } else {
  338. tx[3] = 0x00;
  339. }
  340. memcpy(tx+4, infoHash, 20);
  341. unsigned char x[20];
  342. MessageDigestHelper::digest(x, sizeof(x), "sha1", tx, 24);
  343. while((int32_t)fastSet.size() < fastSetSize) {
  344. for(int32_t i = 0; i < 5 && (int32_t)fastSet.size() < fastSetSize; i++) {
  345. int32_t j = i*4;
  346. uint32_t ny;
  347. memcpy(&ny, x+j, 4);
  348. uint32_t y = ntohl(ny);
  349. int32_t index = y%numPieces;
  350. if(std::find(fastSet.begin(), fastSet.end(), index) == fastSet.end()) {
  351. fastSet.push_back(index);
  352. }
  353. }
  354. unsigned char temp[20];
  355. MessageDigestHelper::digest(temp, sizeof(temp), "sha1", x, sizeof(x));
  356. memcpy(x, temp, sizeof(x));
  357. }
  358. return fastSet;
  359. }
  360. std::ostream& operator<<(std::ostream& o, const DefaultBtContext& ctx)
  361. {
  362. o << "*** BitTorrent File Information ***" << "\n";
  363. o << "Mode: " << (ctx.getFileMode() == DownloadContext::SINGLE ? "Single File Torrent":"Multi File Torrent") << "\n";
  364. o << "Announce:" << "\n";
  365. AnnounceTiers tiers = ctx.getAnnounceTiers();
  366. for(AnnounceTiers::const_iterator itr = tiers.begin(); itr != tiers.end(); ++itr) {
  367. const AnnounceTierHandle& tier = *itr;
  368. for(std::deque<std::string>::const_iterator uriItr = tier->urls.begin(); uriItr != tier->urls.end(); ++uriItr) {
  369. o << " " << *uriItr;
  370. }
  371. o << "\n";
  372. }
  373. o << "Info Hash: " << ctx.getInfoHashAsString() << "\n";
  374. o << "Piece Length: " << Util::abbrevSize(ctx.getPieceLength()) << "B\n";
  375. o << "The Number of Pieces: " << ctx.getNumPieces() << "\n";
  376. o << "Total Length: " << Util::abbrevSize(ctx.getTotalLength()) << "B\n";
  377. if(ctx.getFileMode() == DownloadContext::MULTI) {
  378. o << "Name: " << ctx.getName() << "\n";
  379. }
  380. Util::toStream(o, ctx.getFileEntries());
  381. return o;
  382. }
  383. void DefaultBtContext::setRandomizer(const RandomizerHandle& randomizer)
  384. {
  385. _randomizer = randomizer;
  386. }
  387. } // namespace aria2