DefaultBtContext.cc 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 <libgen.h>
  46. DefaultBtContext::DefaultBtContext():_peerIdPrefix("-aria2-") {}
  47. DefaultBtContext::~DefaultBtContext() {}
  48. string DefaultBtContext::generatePeerId() const {
  49. string peerId = _peerIdPrefix;
  50. peerId += Util::randomAlpha(20-_peerIdPrefix.size());
  51. if(peerId.size() > 20) {
  52. peerId.erase(20);
  53. }
  54. return peerId;
  55. }
  56. const unsigned char* DefaultBtContext::getInfoHash() const {
  57. return infoHash;
  58. }
  59. int32_t DefaultBtContext::getInfoHashLength() const {
  60. return INFO_HASH_LENGTH;
  61. }
  62. string DefaultBtContext::getInfoHashAsString() const {
  63. return infoHashString;
  64. }
  65. void DefaultBtContext::clear() {
  66. memset(infoHash, 0, INFO_HASH_LENGTH);
  67. infoHashString = "";
  68. pieceHashes.clear();
  69. fileEntries.clear();
  70. totalLength = 0;
  71. pieceLength = 0;
  72. fileMode = BtContext::SINGLE;
  73. numPieces = 0;
  74. name = "";
  75. announceTiers.clear();
  76. }
  77. void DefaultBtContext::extractPieceHash(const unsigned char* hashData,
  78. int32_t hashDataLength,
  79. int32_t hashLength) {
  80. assert(hashDataLength > 0);
  81. assert(hashLength > 0);
  82. int32_t numPieces = hashDataLength/hashLength;
  83. assert(numPieces > 0);
  84. for(int32_t i = 0; i < numPieces; i++) {
  85. pieceHashes.push_back(Util::toHex(&hashData[i*hashLength],
  86. hashLength));
  87. }
  88. }
  89. void DefaultBtContext::extractFileEntries(Dictionary* infoDic,
  90. const string& defaultName) {
  91. // TODO use dynamic_cast
  92. Data* nameData = (Data*)infoDic->get("name");
  93. if(nameData) {
  94. name = nameData->toString();
  95. } else {
  96. char* basec = strdup(defaultName.c_str());
  97. name = string(basename(basec))+".file";
  98. free(basec);
  99. }
  100. // TODO use dynamic_cast
  101. List* files = (List*)infoDic->get("files");
  102. if(files) {
  103. int64_t length = 0;
  104. int64_t offset = 0;
  105. // multi-file mode
  106. fileMode = BtContext::MULTI;
  107. const MetaList& metaList = files->getList();
  108. for(MetaList::const_iterator itr = metaList.begin();
  109. itr != metaList.end(); itr++) {
  110. Dictionary* fileDic = (Dictionary*)(*itr);
  111. // TODO use dynamic_cast
  112. Data* lengthData = (Data*)fileDic->get("length");
  113. length += lengthData->toLLInt();
  114. // TODO use dynamic_cast
  115. List* pathList = (List*)fileDic->get("path");
  116. const MetaList& paths = pathList->getList();
  117. string path;
  118. for(int32_t i = 0; i < (int32_t)paths.size()-1; i++) {
  119. Data* subpath = (Data*)paths[i];
  120. path += subpath->toString()+"/";
  121. }
  122. // TODO use dynamic_cast
  123. Data* lastPath = (Data*)paths.back();
  124. path += lastPath->toString();
  125. FileEntryHandle fileEntry(new FileEntry(path,
  126. lengthData->toLLInt(),
  127. offset));
  128. fileEntries.push_back(fileEntry);
  129. offset += fileEntry->getLength();
  130. }
  131. totalLength = length;
  132. } else {
  133. // single-file mode;
  134. fileMode = BtContext::SINGLE;
  135. Data* length = (Data*)infoDic->get("length");
  136. totalLength = length->toLLInt();
  137. FileEntryHandle fileEntry(new FileEntry(name, totalLength, 0));
  138. fileEntries.push_back(fileEntry);
  139. }
  140. }
  141. void DefaultBtContext::extractAnnounce(Data* announceData) {
  142. Strings urls;
  143. urls.push_back(announceData->toString());
  144. announceTiers.push_back(AnnounceTierHandle(new AnnounceTier(urls)));
  145. }
  146. void DefaultBtContext::extractAnnounceList(List* announceListData) {
  147. for(MetaList::const_iterator itr = announceListData->getList().begin();
  148. itr != announceListData->getList().end(); itr++) {
  149. const List* elem = (List*)*itr;
  150. Strings urls;
  151. for(MetaList::const_iterator elemItr = elem->getList().begin();
  152. elemItr != elem->getList().end(); elemItr++) {
  153. const Data* data = (Data*)*elemItr;
  154. urls.push_back(data->toString());
  155. }
  156. if(urls.size()) {
  157. AnnounceTierHandle tier(new AnnounceTier(urls));
  158. announceTiers.push_back(tier);
  159. }
  160. }
  161. }
  162. void DefaultBtContext::load(const string& torrentFile) {
  163. clear();
  164. MetaEntry* rootEntry = MetaFileUtil::parseMetaFile(torrentFile);
  165. if(!dynamic_cast<Dictionary*>(rootEntry)) {
  166. throw new DlAbortEx("torrent file does not contain a root dictionary .");
  167. }
  168. SharedHandle<Dictionary> rootDic =
  169. SharedHandle<Dictionary>((Dictionary*)rootEntry);
  170. Dictionary* infoDic = (Dictionary*)rootDic->get("info");
  171. // retrieve infoHash
  172. ShaVisitor v;
  173. infoDic->accept(&v);
  174. int32_t len;
  175. v.getHash(infoHash, len);
  176. infoHashString = Util::toHex(infoHash, INFO_HASH_LENGTH);
  177. // calculate the number of pieces
  178. Data* pieceHashData = (Data*)infoDic->get("pieces");
  179. numPieces = pieceHashData->getLen()/PIECE_HASH_LENGTH;
  180. // retrieve piece length
  181. Data* pieceLengthData = (Data*)infoDic->get("piece length");
  182. pieceLength = pieceLengthData->toInt();
  183. // retrieve piece hashes
  184. extractPieceHash((unsigned char*)pieceHashData->getData(),
  185. pieceHashData->getLen(),
  186. PIECE_HASH_LENGTH);
  187. // retrieve file entries
  188. extractFileEntries(infoDic, torrentFile);
  189. // retrieve announce
  190. Data* announceData = (Data*)rootDic->get("announce");
  191. List* announceListData = (List*)rootDic->get("announce-list");
  192. if(announceListData) {
  193. extractAnnounceList(announceListData);
  194. } else if(announceData) {
  195. extractAnnounce(announceData);
  196. }
  197. if(!announceTiers.size()) {
  198. throw new DlAbortEx("No announce URL found.");
  199. }
  200. }
  201. string DefaultBtContext::getPieceHash(int32_t index) const {
  202. if(index < 0 || numPieces <= index) {
  203. return "";
  204. }
  205. return pieceHashes[index];
  206. }
  207. int64_t DefaultBtContext::getTotalLength() const {
  208. return totalLength;
  209. }
  210. BtContext::FILE_MODE DefaultBtContext::getFileMode() const {
  211. return fileMode;
  212. }
  213. FileEntries DefaultBtContext::getFileEntries() const {
  214. return fileEntries;
  215. }
  216. AnnounceTiers DefaultBtContext::getAnnounceTiers() const {
  217. return announceTiers;
  218. }
  219. string DefaultBtContext::getName() const {
  220. return name;
  221. }
  222. int32_t DefaultBtContext::getPieceLength() const {
  223. return pieceLength;
  224. }
  225. int32_t DefaultBtContext::getNumPieces() const {
  226. return numPieces;
  227. }
  228. Integers DefaultBtContext::computeFastSet(const string& ipaddr, int32_t fastSetSize)
  229. {
  230. Integers fastSet;
  231. struct in_addr saddr;
  232. if(inet_aton(ipaddr.c_str(), &saddr) == 0) {
  233. abort();
  234. }
  235. unsigned char tx[24];
  236. memcpy(tx, (void*)&saddr.s_addr, 4);
  237. if((tx[0] & 0x80) == 0 || (tx[0] & 0x40) == 0) {
  238. tx[2] = 0x00;
  239. tx[3] = 0x00;
  240. } else {
  241. tx[3] = 0x00;
  242. }
  243. memcpy(tx+4, infoHash, 20);
  244. unsigned char x[20];
  245. MessageDigestHelper::digest(x, sizeof(x), "sha1", tx, 24);
  246. while((int32_t)fastSet.size() < fastSetSize) {
  247. for(int32_t i = 0; i < 5 && (int32_t)fastSet.size() < fastSetSize; i++) {
  248. int32_t j = i*4;
  249. uint32_t ny;
  250. memcpy(&ny, x+j, 4);
  251. uint32_t y = ntohl(ny);
  252. int32_t index = y%numPieces;
  253. if(find(fastSet.begin(), fastSet.end(), index) == fastSet.end()) {
  254. fastSet.push_back(index);
  255. }
  256. }
  257. unsigned char temp[20];
  258. MessageDigestHelper::digest(temp, sizeof(temp), "sha1", x, sizeof(x));
  259. memcpy(x, temp, sizeof(x));
  260. }
  261. return fastSet;
  262. }