DefaultBtContext.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 "ShaVisitor.h"
  42. #include "Util.h"
  43. #include "MessageDigestHelper.h"
  44. #include "a2netcompat.h"
  45. #include "AnnounceTier.h"
  46. #include "SimpleRandomizer.h"
  47. #include <libgen.h>
  48. DefaultBtContext::DefaultBtContext():_peerIdPrefix("-aria2-"),
  49. _randomizer(SimpleRandomizer::getInstance()),
  50. _ownerRequestGroup(0) {}
  51. DefaultBtContext::~DefaultBtContext() {}
  52. string DefaultBtContext::generatePeerId() const {
  53. string peerId = _peerIdPrefix;
  54. peerId += Util::randomAlpha(20-_peerIdPrefix.size(), _randomizer);
  55. if(peerId.size() > 20) {
  56. peerId.erase(20);
  57. }
  58. return peerId;
  59. }
  60. const unsigned char* DefaultBtContext::getInfoHash() const {
  61. return infoHash;
  62. }
  63. int32_t DefaultBtContext::getInfoHashLength() const {
  64. return INFO_HASH_LENGTH;
  65. }
  66. string DefaultBtContext::getInfoHashAsString() const {
  67. return infoHashString;
  68. }
  69. void DefaultBtContext::clear() {
  70. memset(infoHash, 0, INFO_HASH_LENGTH);
  71. infoHashString = "";
  72. pieceHashes.clear();
  73. fileEntries.clear();
  74. totalLength = 0;
  75. pieceLength = 0;
  76. fileMode = BtContext::SINGLE;
  77. numPieces = 0;
  78. name = "";
  79. announceTiers.clear();
  80. }
  81. void DefaultBtContext::extractPieceHash(const unsigned char* hashData,
  82. int32_t hashDataLength,
  83. int32_t hashLength) {
  84. assert(hashDataLength > 0);
  85. assert(hashLength > 0);
  86. int32_t numPieces = hashDataLength/hashLength;
  87. assert(numPieces > 0);
  88. for(int32_t i = 0; i < numPieces; i++) {
  89. pieceHashes.push_back(Util::toHex(&hashData[i*hashLength],
  90. hashLength));
  91. }
  92. }
  93. void DefaultBtContext::extractFileEntries(Dictionary* infoDic,
  94. const string& defaultName,
  95. const Strings& urlList) {
  96. // TODO use dynamic_cast
  97. Data* nameData = (Data*)infoDic->get("name");
  98. if(nameData) {
  99. name = nameData->toString();
  100. } else {
  101. char* basec = strdup(defaultName.c_str());
  102. name = string(basename(basec))+".file";
  103. free(basec);
  104. }
  105. // TODO use dynamic_cast
  106. List* files = (List*)infoDic->get("files");
  107. if(files) {
  108. int64_t length = 0;
  109. int64_t offset = 0;
  110. // multi-file mode
  111. fileMode = BtContext::MULTI;
  112. const MetaList& metaList = files->getList();
  113. for(MetaList::const_iterator itr = metaList.begin();
  114. itr != metaList.end(); itr++) {
  115. Dictionary* fileDic = (Dictionary*)(*itr);
  116. // TODO use dynamic_cast
  117. Data* lengthData = (Data*)fileDic->get("length");
  118. length += lengthData->toLLInt();
  119. // TODO use dynamic_cast
  120. List* pathList = (List*)fileDic->get("path");
  121. const MetaList& paths = pathList->getList();
  122. string path;
  123. for(int32_t i = 0; i < (int32_t)paths.size()-1; i++) {
  124. Data* subpath = (Data*)paths[i];
  125. path += subpath->toString()+"/";
  126. }
  127. // TODO use dynamic_cast
  128. Data* lastPath = (Data*)paths.back();
  129. path += lastPath->toString();
  130. Strings uris;
  131. transform(urlList.begin(), urlList.end(), back_inserter(uris),
  132. bind2nd(plus<string>(), "/"+name+"/"+path));
  133. FileEntryHandle fileEntry(new FileEntry(path,
  134. lengthData->toLLInt(),
  135. offset,
  136. uris));
  137. fileEntries.push_back(fileEntry);
  138. offset += fileEntry->getLength();
  139. }
  140. totalLength = length;
  141. } else {
  142. // single-file mode;
  143. fileMode = BtContext::SINGLE;
  144. Data* length = (Data*)infoDic->get("length");
  145. totalLength = length->toLLInt();
  146. FileEntryHandle fileEntry(new FileEntry(name, totalLength, 0, urlList));
  147. fileEntries.push_back(fileEntry);
  148. }
  149. }
  150. void DefaultBtContext::extractAnnounce(Data* announceData) {
  151. Strings urls;
  152. urls.push_back(announceData->toString());
  153. announceTiers.push_back(AnnounceTierHandle(new AnnounceTier(urls)));
  154. }
  155. void DefaultBtContext::extractAnnounceList(List* announceListData) {
  156. for(MetaList::const_iterator itr = announceListData->getList().begin();
  157. itr != announceListData->getList().end(); itr++) {
  158. const List* elem = (List*)*itr;
  159. Strings urls;
  160. for(MetaList::const_iterator elemItr = elem->getList().begin();
  161. elemItr != elem->getList().end(); elemItr++) {
  162. const Data* data = (Data*)*elemItr;
  163. urls.push_back(data->toString());
  164. }
  165. if(urls.size()) {
  166. AnnounceTierHandle tier(new AnnounceTier(urls));
  167. announceTiers.push_back(tier);
  168. }
  169. }
  170. }
  171. Strings DefaultBtContext::extractUrlList(const MetaEntry* obj)
  172. {
  173. Strings uris;
  174. if(dynamic_cast<const List*>(obj)) {
  175. const List* urlList = (const List*)obj;
  176. for(MetaList::const_iterator itr = urlList->getList().begin();
  177. itr != urlList->getList().end(); ++itr) {
  178. Data* data = dynamic_cast<Data*>(*itr);
  179. if(data) {
  180. uris.push_back(data->toString());
  181. }
  182. }
  183. } else if(dynamic_cast<const Data*>(obj)) {
  184. const Data* urlData = (const Data*)obj;
  185. uris.push_back(urlData->toString());
  186. }
  187. return uris;
  188. }
  189. void DefaultBtContext::load(const string& torrentFile) {
  190. clear();
  191. MetaEntry* rootEntry = MetaFileUtil::parseMetaFile(torrentFile);
  192. if(!dynamic_cast<Dictionary*>(rootEntry)) {
  193. throw new DlAbortEx("torrent file does not contain a root dictionary .");
  194. }
  195. SharedHandle<Dictionary> rootDic =
  196. SharedHandle<Dictionary>((Dictionary*)rootEntry);
  197. Dictionary* infoDic = (Dictionary*)rootDic->get("info");
  198. // retrieve infoHash
  199. ShaVisitor v;
  200. infoDic->accept(&v);
  201. int len;
  202. v.getHash(infoHash, len);
  203. infoHashString = Util::toHex(infoHash, INFO_HASH_LENGTH);
  204. // calculate the number of pieces
  205. Data* pieceHashData = (Data*)infoDic->get("pieces");
  206. numPieces = pieceHashData->getLen()/PIECE_HASH_LENGTH;
  207. // retrieve piece length
  208. Data* pieceLengthData = (Data*)infoDic->get("piece length");
  209. pieceLength = pieceLengthData->toInt();
  210. // retrieve piece hashes
  211. extractPieceHash((unsigned char*)pieceHashData->getData(),
  212. pieceHashData->getLen(),
  213. PIECE_HASH_LENGTH);
  214. // retrieve uri-list.
  215. // This implemantation obeys HTTP-Seeding specification:
  216. // see http://www.getright.com/seedtorrent.html
  217. Strings urlList = extractUrlList(rootDic->get("url-list"));
  218. // retrieve file entries
  219. extractFileEntries(infoDic, torrentFile, urlList);
  220. // retrieve announce
  221. Data* announceData = (Data*)rootDic->get("announce");
  222. List* announceListData = (List*)rootDic->get("announce-list");
  223. if(announceListData) {
  224. extractAnnounceList(announceListData);
  225. } else if(announceData) {
  226. extractAnnounce(announceData);
  227. }
  228. if(!announceTiers.size()) {
  229. throw new DlAbortEx("No announce URL found.");
  230. }
  231. }
  232. string DefaultBtContext::getPieceHash(int32_t index) const {
  233. if(index < 0 || numPieces <= index) {
  234. return "";
  235. }
  236. return pieceHashes[index];
  237. }
  238. int64_t DefaultBtContext::getTotalLength() const {
  239. return totalLength;
  240. }
  241. BtContext::FILE_MODE DefaultBtContext::getFileMode() const {
  242. return fileMode;
  243. }
  244. FileEntries DefaultBtContext::getFileEntries() const {
  245. return fileEntries;
  246. }
  247. AnnounceTiers DefaultBtContext::getAnnounceTiers() const {
  248. return announceTiers;
  249. }
  250. string DefaultBtContext::getName() const {
  251. return name;
  252. }
  253. int32_t DefaultBtContext::getPieceLength() const {
  254. return pieceLength;
  255. }
  256. int32_t DefaultBtContext::getNumPieces() const {
  257. return numPieces;
  258. }
  259. string DefaultBtContext::getActualBasePath() const
  260. {
  261. return _dir+"/"+name;
  262. }
  263. Integers DefaultBtContext::computeFastSet(const string& ipaddr, int32_t fastSetSize)
  264. {
  265. Integers fastSet;
  266. struct in_addr saddr;
  267. if(inet_aton(ipaddr.c_str(), &saddr) == 0) {
  268. abort();
  269. }
  270. unsigned char tx[24];
  271. memcpy(tx, (void*)&saddr.s_addr, 4);
  272. if((tx[0] & 0x80) == 0 || (tx[0] & 0x40) == 0) {
  273. tx[2] = 0x00;
  274. tx[3] = 0x00;
  275. } else {
  276. tx[3] = 0x00;
  277. }
  278. memcpy(tx+4, infoHash, 20);
  279. unsigned char x[20];
  280. MessageDigestHelper::digest(x, sizeof(x), "sha1", tx, 24);
  281. while((int32_t)fastSet.size() < fastSetSize) {
  282. for(int32_t i = 0; i < 5 && (int32_t)fastSet.size() < fastSetSize; i++) {
  283. int32_t j = i*4;
  284. uint32_t ny;
  285. memcpy(&ny, x+j, 4);
  286. uint32_t y = ntohl(ny);
  287. int32_t index = y%numPieces;
  288. if(find(fastSet.begin(), fastSet.end(), index) == fastSet.end()) {
  289. fastSet.push_back(index);
  290. }
  291. }
  292. unsigned char temp[20];
  293. MessageDigestHelper::digest(temp, sizeof(temp), "sha1", x, sizeof(x));
  294. memcpy(x, temp, sizeof(x));
  295. }
  296. return fastSet;
  297. }
  298. ostream& operator<<(ostream& o, const DefaultBtContext& ctx)
  299. {
  300. o << "*** BitTorrent File Information ***" << "\n";
  301. o << "Mode: " << (ctx.getFileMode() == DownloadContext::SINGLE ? "Single File Torrent":"Multi File Torrent") << "\n";
  302. o << "Announce:" << "\n";
  303. AnnounceTiers tiers = ctx.getAnnounceTiers();
  304. for(AnnounceTiers::const_iterator itr = tiers.begin(); itr != tiers.end(); ++itr) {
  305. const AnnounceTierHandle& tier = *itr;
  306. for(Strings::const_iterator uriItr = tier->urls.begin(); uriItr != tier->urls.end(); ++uriItr) {
  307. o << " " << *uriItr;
  308. }
  309. o << "\n";
  310. }
  311. o << "Info Hash: " << ctx.getInfoHashAsString() << "\n";
  312. o << "Piece Length: " << Util::abbrevSize(ctx.getPieceLength()) << "B\n";
  313. o << "The Number of Pieces: " << ctx.getNumPieces() << "\n";
  314. o << "Total Length: " << Util::abbrevSize(ctx.getTotalLength()) << "B\n";
  315. if(ctx.getFileMode() == DownloadContext::MULTI) {
  316. o << "Name: " << ctx.getName() << "\n";
  317. }
  318. Util::toStream(o, ctx.getFileEntries());
  319. return o;
  320. }
  321. void DefaultBtContext::setRandomizer(const RandomizerHandle& randomizer)
  322. {
  323. _randomizer = randomizer;
  324. }