bittorrent_helper.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2009 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 "bittorrent_helper.h"
  36. #include <cassert>
  37. #include <cstring>
  38. #include <algorithm>
  39. #include "DownloadContext.h"
  40. #include "Randomizer.h"
  41. #include "bencode.h"
  42. #include "util.h"
  43. #include "DlAbortEx.h"
  44. #include "message.h"
  45. #include "StringFormat.h"
  46. #include "BtConstants.h"
  47. #include "messageDigest.h"
  48. #include "MessageDigestHelper.h"
  49. #include "SimpleRandomizer.h"
  50. #include "a2netcompat.h"
  51. #include "BtConstants.h"
  52. #include "bitfield.h"
  53. namespace aria2 {
  54. namespace bittorrent {
  55. static const std::string C_NAME("name");
  56. static const std::string C_NAME_UTF8("name.utf-8");
  57. static const std::string C_FILES("files");
  58. static const std::string C_LENGTH("length");
  59. static const std::string C_PATH("path");
  60. static const std::string C_PATH_UTF8("path.utf-8");
  61. static const std::string C_INFO("info");
  62. static const std::string C_PIECES("pieces");
  63. static const std::string C_PIECE_LENGTH("piece length");
  64. static const std::string C_PRIVATE("private");
  65. static const std::string C_URL_LIST("url-list");
  66. static const std::string C_ANNOUNCE("announce");
  67. static const std::string C_ANNOUNCE_LIST("announce-list");
  68. static const std::string C_NODES("nodes");
  69. static const std::string C_CREATION_DATE("creation date");
  70. static const std::string C_COMMENT("comment");
  71. static const std::string C_COMMENT_UTF8("comment.utf-8");
  72. static const std::string C_CREATED_BY("created by");
  73. static const std::string DEFAULT_PEER_ID_PREFIX("aria2-");
  74. const std::string INFO_HASH("infoHash");
  75. const std::string MODE("mode");
  76. const std::string PRIVATE("private");
  77. const std::string ANNOUNCE_LIST("announceList");
  78. const std::string NODES("nodes");
  79. const std::string HOSTNAME("hostname");
  80. const std::string PORT("port");
  81. const std::string NAME("name");
  82. const std::string URL_LIST("urlList");
  83. const std::string CREATION_DATE("creationDate");
  84. const std::string COMMENT("comment");
  85. const std::string CREATED_BY("createdBy");
  86. const std::string BITTORRENT("bittorrent");
  87. const std::string MULTI("multi");
  88. const std::string SINGLE("single");
  89. const std::string METADATA_SIZE("metadataSize");
  90. const std::string METADATA("metadata");
  91. static void extractPieceHash(const SharedHandle<DownloadContext>& ctx,
  92. const std::string& hashData,
  93. size_t hashLength,
  94. size_t numPieces)
  95. {
  96. std::vector<std::string> pieceHashes;
  97. pieceHashes.reserve(numPieces);
  98. for(size_t i = 0; i < numPieces; ++i) {
  99. pieceHashes.push_back(util::toHex(hashData.data()+i*hashLength,
  100. hashLength));
  101. }
  102. ctx->setPieceHashes(pieceHashes.begin(), pieceHashes.end());
  103. ctx->setPieceHashAlgo(MessageDigestContext::SHA1);
  104. }
  105. static void extractUrlList
  106. (BDE& torrent, std::vector<std::string>& uris, const BDE& bde)
  107. {
  108. if(bde.isList()) {
  109. for(BDE::List::const_iterator itr = bde.listBegin();
  110. itr != bde.listEnd(); ++itr) {
  111. if((*itr).isString()) {
  112. uris.push_back((*itr).s());
  113. }
  114. }
  115. torrent[URL_LIST] = bde;
  116. } else if(bde.isString()) {
  117. uris.push_back(bde.s());
  118. BDE urlList = BDE::list();
  119. urlList << bde;
  120. torrent[URL_LIST] = urlList;
  121. } else {
  122. torrent[URL_LIST] = BDE::list();
  123. }
  124. }
  125. template<typename InputIterator, typename OutputIterator>
  126. static OutputIterator createUri
  127. (InputIterator first, InputIterator last, OutputIterator out,
  128. const std::string& filePath)
  129. {
  130. for(; first != last; ++first) {
  131. if(util::endsWith(*first, "/")) {
  132. *out++ = (*first)+filePath;
  133. } else {
  134. *out++ = (*first)+"/"+filePath;
  135. }
  136. }
  137. return out;
  138. }
  139. static void extractFileEntries
  140. (const SharedHandle<DownloadContext>& ctx,
  141. BDE& torrent,
  142. const BDE& infoDict,
  143. const std::string& defaultName,
  144. const std::string& overrideName,
  145. const std::vector<std::string>& urlList)
  146. {
  147. std::string name;
  148. if(overrideName.empty()) {
  149. std::string nameKey;
  150. if(infoDict.containsKey(C_NAME_UTF8)) {
  151. nameKey = C_NAME_UTF8;
  152. } else {
  153. nameKey = C_NAME;
  154. }
  155. const BDE& nameData = infoDict[nameKey];
  156. if(nameData.isString()) {
  157. // Split path by '/' just in case nasty ".." is included in name
  158. std::vector<std::string> pathelems;
  159. util::split(nameData.s(), std::back_inserter(pathelems), "/");
  160. name = util::joinPath(pathelems.begin(), pathelems.end());
  161. torrent[NAME] = nameData.s();
  162. } else {
  163. name = strconcat(File(defaultName).getBasename(), ".file");
  164. torrent[NAME] = name;
  165. }
  166. } else {
  167. name = overrideName;
  168. torrent[NAME] = name;
  169. }
  170. const BDE& filesList = infoDict[C_FILES];
  171. std::vector<SharedHandle<FileEntry> > fileEntries;
  172. if(filesList.isList()) {
  173. fileEntries.reserve(filesList.size());
  174. uint64_t length = 0;
  175. off_t offset = 0;
  176. // multi-file mode
  177. torrent[MODE] = MULTI;
  178. for(BDE::List::const_iterator itr = filesList.listBegin();
  179. itr != filesList.listEnd(); ++itr) {
  180. const BDE& fileDict = *itr;
  181. if(!fileDict.isDict()) {
  182. continue;
  183. }
  184. const BDE& fileLengthData = fileDict[C_LENGTH];
  185. if(!fileLengthData.isInteger()) {
  186. throw DL_ABORT_EX(StringFormat(MSG_MISSING_BT_INFO,
  187. C_LENGTH.c_str()).str());
  188. }
  189. length += fileLengthData.i();
  190. std::string pathKey;
  191. if(fileDict.containsKey(C_PATH_UTF8)) {
  192. pathKey = C_PATH_UTF8;
  193. } else {
  194. pathKey = C_PATH;
  195. }
  196. const BDE& pathList = fileDict[pathKey];
  197. if(!pathList.isList() || pathList.empty()) {
  198. throw DL_ABORT_EX("Path is empty.");
  199. }
  200. std::vector<std::string> pathelem(pathList.size());
  201. std::transform(pathList.listBegin(), pathList.listEnd(), pathelem.begin(),
  202. std::mem_fun_ref(&BDE::s));
  203. std::string path = name;
  204. strappend(path, "/", util::joinPath(pathelem.begin(), pathelem.end()));
  205. // Split path with '/' again because each pathList element can
  206. // contain "/" inside.
  207. std::vector<std::string> elements;
  208. util::split(path, std::back_inserter(elements), "/");
  209. path = util::joinPath(elements.begin(), elements.end());
  210. std::deque<std::string> uris;
  211. createUri(urlList.begin(), urlList.end(), std::back_inserter(uris), path);
  212. SharedHandle<FileEntry> fileEntry
  213. (new FileEntry(strconcat(ctx->getDir(), "/", path),
  214. fileLengthData.i(),
  215. offset, uris));
  216. fileEntries.push_back(fileEntry);
  217. offset += fileEntry->getLength();
  218. }
  219. } else {
  220. // single-file mode;
  221. torrent[MODE] = SINGLE;
  222. const BDE& lengthData = infoDict[C_LENGTH];
  223. if(!lengthData.isInteger()) {
  224. throw DL_ABORT_EX(StringFormat(MSG_MISSING_BT_INFO,
  225. C_LENGTH.c_str()).str());
  226. }
  227. uint64_t totalLength = lengthData.i();
  228. // For each uri in urlList, if it ends with '/', then
  229. // concatenate name to it. Specification just says so.
  230. std::deque<std::string> uris;
  231. for(std::vector<std::string>::const_iterator i = urlList.begin();
  232. i != urlList.end(); ++i) {
  233. if(util::endsWith(*i, "/")) {
  234. uris.push_back((*i)+name);
  235. } else {
  236. uris.push_back(*i);
  237. }
  238. }
  239. SharedHandle<FileEntry> fileEntry
  240. (new FileEntry(strconcat(ctx->getDir(), "/", name),totalLength, 0,
  241. uris));
  242. fileEntries.push_back(fileEntry);
  243. }
  244. ctx->setFileEntries(fileEntries.begin(), fileEntries.end());
  245. if(torrent[MODE].s() == MULTI) {
  246. ctx->setBasePath(strconcat(ctx->getDir(), "/", name));
  247. }
  248. }
  249. static void extractAnnounce(BDE& torrent, const BDE& rootDict)
  250. {
  251. const BDE& announceList = rootDict[C_ANNOUNCE_LIST];
  252. if(announceList.isList()) {
  253. torrent[ANNOUNCE_LIST] = announceList;
  254. } else {
  255. const BDE& announce = rootDict[C_ANNOUNCE];
  256. BDE announceList = BDE::list();
  257. if(announce.isString()) {
  258. announceList << BDE::list();
  259. announceList[0] << announce;
  260. }
  261. torrent[ANNOUNCE_LIST] = announceList;
  262. }
  263. }
  264. static void extractNodes(BDE& torrent, const BDE& nodesList)
  265. {
  266. BDE nodes = BDE::list();
  267. if(nodesList.isList()) {
  268. for(BDE::List::const_iterator i = nodesList.listBegin();
  269. i != nodesList.listEnd(); ++i) {
  270. const BDE& addrPairList = (*i);
  271. if(!addrPairList.isList() || addrPairList.size() != 2) {
  272. continue;
  273. }
  274. const BDE& hostname = addrPairList[0];
  275. if(!hostname.isString()) {
  276. continue;
  277. }
  278. if(util::trim(hostname.s()).empty()) {
  279. continue;
  280. }
  281. const BDE& port = addrPairList[1];
  282. if(!port.isInteger() || !(0 < port.i() && port.i() < 65536)) {
  283. continue;
  284. }
  285. BDE node = BDE::dict();
  286. node[HOSTNAME] = hostname;
  287. node[PORT] = port;
  288. nodes << node;
  289. }
  290. }
  291. torrent[NODES] = nodes;
  292. }
  293. static void processRootDictionary
  294. (const SharedHandle<DownloadContext>& ctx,
  295. const BDE& rootDict,
  296. const std::string& defaultName,
  297. const std::string& overrideName,
  298. const std::deque<std::string>& uris)
  299. {
  300. if(!rootDict.isDict()) {
  301. throw DL_ABORT_EX("torrent file does not contain a root dictionary.");
  302. }
  303. const BDE& infoDict = rootDict[C_INFO];
  304. if(!infoDict.isDict()) {
  305. throw DL_ABORT_EX(StringFormat(MSG_MISSING_BT_INFO,
  306. C_INFO.c_str()).str());
  307. }
  308. BDE torrent = BDE::dict();
  309. // retrieve infoHash
  310. std::string encodedInfoDict = bencode::encode(infoDict);
  311. unsigned char infoHash[INFO_HASH_LENGTH];
  312. MessageDigestHelper::digest(infoHash, INFO_HASH_LENGTH,
  313. MessageDigestContext::SHA1,
  314. encodedInfoDict.data(),
  315. encodedInfoDict.size());
  316. torrent[INFO_HASH] = std::string(&infoHash[0], &infoHash[INFO_HASH_LENGTH]);
  317. torrent[METADATA] = encodedInfoDict;
  318. torrent[METADATA_SIZE] = encodedInfoDict.size();
  319. // calculate the number of pieces
  320. const BDE& piecesData = infoDict[C_PIECES];
  321. if(!piecesData.isString()) {
  322. throw DL_ABORT_EX(StringFormat(MSG_MISSING_BT_INFO,
  323. C_PIECES.c_str()).str());
  324. }
  325. // Commented out To download 0 length torrent.
  326. // if(piecesData.s().empty()) {
  327. // throw DL_ABORT_EX("The length of piece hash is 0.");
  328. // }
  329. size_t numPieces = piecesData.s().size()/PIECE_HASH_LENGTH;
  330. // Commented out to download 0 length torrent.
  331. // if(numPieces == 0) {
  332. // throw DL_ABORT_EX("The number of pieces is 0.");
  333. // }
  334. // retrieve piece length
  335. const BDE& pieceLengthData = infoDict[C_PIECE_LENGTH];
  336. if(!pieceLengthData.isInteger()) {
  337. throw DL_ABORT_EX(StringFormat(MSG_MISSING_BT_INFO,
  338. C_PIECE_LENGTH.c_str()).str());
  339. }
  340. size_t pieceLength = pieceLengthData.i();
  341. ctx->setPieceLength(pieceLength);
  342. // retrieve piece hashes
  343. extractPieceHash(ctx, piecesData.s(), PIECE_HASH_LENGTH, numPieces);
  344. // private flag
  345. const BDE& privateData = infoDict[C_PRIVATE];
  346. int privatefg = 0;
  347. if(privateData.isInteger()) {
  348. if(privateData.i() == 1) {
  349. privatefg = 1;
  350. }
  351. }
  352. torrent[PRIVATE] = BDE((int64_t)privatefg);
  353. // retrieve uri-list.
  354. // This implemantation obeys HTTP-Seeding specification:
  355. // see http://www.getright.com/seedtorrent.html
  356. std::vector<std::string> urlList;
  357. extractUrlList(torrent, urlList, rootDict[C_URL_LIST]);
  358. urlList.insert(urlList.end(), uris.begin(), uris.end());
  359. std::sort(urlList.begin(), urlList.end());
  360. urlList.erase(std::unique(urlList.begin(), urlList.end()), urlList.end());
  361. // retrieve file entries
  362. extractFileEntries(ctx, torrent, infoDict, defaultName, overrideName, urlList);
  363. if((ctx->getTotalLength()+pieceLength-1)/pieceLength != numPieces) {
  364. throw DL_ABORT_EX("Too few/many piece hash.");
  365. }
  366. // retrieve announce
  367. extractAnnounce(torrent, rootDict);
  368. // retrieve nodes
  369. extractNodes(torrent, rootDict[C_NODES]);
  370. const BDE& creationDate = rootDict[C_CREATION_DATE];
  371. if(creationDate.isInteger()) {
  372. torrent[CREATION_DATE] = creationDate;
  373. }
  374. const BDE& commentUtf8 = rootDict[C_COMMENT_UTF8];
  375. if(commentUtf8.isString()) {
  376. torrent[COMMENT] = commentUtf8;
  377. } else {
  378. const BDE& comment = rootDict[C_COMMENT];
  379. if(comment.isString()) {
  380. torrent[COMMENT] = comment;
  381. }
  382. }
  383. const BDE& createdBy = rootDict[C_CREATED_BY];
  384. if(createdBy.isString()) {
  385. torrent[CREATED_BY] = createdBy;
  386. }
  387. ctx->setAttribute(BITTORRENT, torrent);
  388. }
  389. void load(const std::string& torrentFile,
  390. const SharedHandle<DownloadContext>& ctx,
  391. const std::string& overrideName)
  392. {
  393. processRootDictionary(ctx,
  394. bencode::decodeFromFile(torrentFile),
  395. torrentFile,
  396. overrideName,
  397. std::deque<std::string>());
  398. }
  399. void load(const std::string& torrentFile,
  400. const SharedHandle<DownloadContext>& ctx,
  401. const std::deque<std::string>& uris,
  402. const std::string& overrideName)
  403. {
  404. processRootDictionary(ctx,
  405. bencode::decodeFromFile(torrentFile),
  406. torrentFile,
  407. overrideName,
  408. uris);
  409. }
  410. void loadFromMemory(const unsigned char* content,
  411. size_t length,
  412. const SharedHandle<DownloadContext>& ctx,
  413. const std::string& defaultName,
  414. const std::string& overrideName)
  415. {
  416. processRootDictionary(ctx,
  417. bencode::decode(content, length),
  418. defaultName,
  419. overrideName,
  420. std::deque<std::string>());
  421. }
  422. void loadFromMemory(const unsigned char* content,
  423. size_t length,
  424. const SharedHandle<DownloadContext>& ctx,
  425. const std::deque<std::string>& uris,
  426. const std::string& defaultName,
  427. const std::string& overrideName)
  428. {
  429. processRootDictionary(ctx,
  430. bencode::decode(content, length),
  431. defaultName,
  432. overrideName,
  433. uris);
  434. }
  435. void loadFromMemory(const std::string& context,
  436. const SharedHandle<DownloadContext>& ctx,
  437. const std::string& defaultName,
  438. const std::string& overrideName)
  439. {
  440. processRootDictionary
  441. (ctx,
  442. bencode::decode(context),
  443. defaultName, overrideName,
  444. std::deque<std::string>());
  445. }
  446. void loadFromMemory(const std::string& context,
  447. const SharedHandle<DownloadContext>& ctx,
  448. const std::deque<std::string>& uris,
  449. const std::string& defaultName,
  450. const std::string& overrideName)
  451. {
  452. processRootDictionary
  453. (ctx,
  454. bencode::decode(context),
  455. defaultName, overrideName,
  456. uris);
  457. }
  458. const unsigned char*
  459. getInfoHash(const SharedHandle<DownloadContext>& downloadContext)
  460. {
  461. return downloadContext->getAttribute(BITTORRENT)[INFO_HASH].uc();
  462. }
  463. std::string
  464. getInfoHashString(const SharedHandle<DownloadContext>& downloadContext)
  465. {
  466. return util::toHex(downloadContext->getAttribute(BITTORRENT)[INFO_HASH].s());
  467. }
  468. void print(std::ostream& o, const SharedHandle<DownloadContext>& dctx)
  469. {
  470. const BDE& torrentAttrs = dctx->getAttribute(BITTORRENT);
  471. o << "*** BitTorrent File Information ***" << "\n";
  472. if(torrentAttrs.containsKey(COMMENT)) {
  473. o << "Comment: " << torrentAttrs[COMMENT].s() << "\n";
  474. }
  475. if(torrentAttrs.containsKey(CREATION_DATE)) {
  476. struct tm* staticNowtmPtr;
  477. char buf[26];
  478. time_t t = torrentAttrs[CREATION_DATE].i();
  479. if((staticNowtmPtr = localtime(&t)) != 0 &&
  480. asctime_r(staticNowtmPtr, buf) != 0) {
  481. // buf includes "\n"
  482. o << "Creation Date: " << buf;
  483. }
  484. }
  485. if(torrentAttrs.containsKey(CREATED_BY)) {
  486. o << "Created By: " << torrentAttrs[CREATED_BY].s() << "\n";
  487. }
  488. o << "Mode: " << torrentAttrs[MODE].s() << "\n";
  489. o << "Announce:" << "\n";
  490. const BDE& announceList = torrentAttrs[ANNOUNCE_LIST];
  491. for(BDE::List::const_iterator tieritr = announceList.listBegin();
  492. tieritr != announceList.listEnd(); ++tieritr) {
  493. if(!(*tieritr).isList()) {
  494. continue;
  495. }
  496. for(BDE::List::const_iterator i = (*tieritr).listBegin();
  497. i != (*tieritr).listEnd(); ++i) {
  498. o << " " << (*i).s();
  499. }
  500. o << "\n";
  501. }
  502. o << "Info Hash: " << util::toHex(torrentAttrs[INFO_HASH].s()) << "\n";
  503. o << "Piece Length: " << util::abbrevSize(dctx->getPieceLength()) << "B\n";
  504. o << "The Number of Pieces: " << dctx->getNumPieces() << "\n";
  505. o << "Total Length: " << util::abbrevSize(dctx->getTotalLength()) << "B ("
  506. << util::uitos(dctx->getTotalLength(), true) << ")\n";
  507. if(!torrentAttrs[URL_LIST].empty()) {
  508. const BDE& urlList = torrentAttrs[URL_LIST];
  509. o << "URL List: " << "\n";
  510. for(BDE::List::const_iterator i = urlList.listBegin();
  511. i != urlList.listEnd(); ++i) {
  512. o << " " << (*i).s() << "\n";
  513. }
  514. }
  515. o << "Name: " << torrentAttrs[NAME].s() << "\n";
  516. util::toStream(dctx->getFileEntries().begin(), dctx->getFileEntries().end(), o);
  517. }
  518. void computeFastSet
  519. (std::vector<size_t>& fastSet, const std::string& ipaddr,
  520. size_t numPieces, const unsigned char* infoHash, size_t fastSetSize)
  521. {
  522. unsigned char compact[6];
  523. if(!createcompact(compact, ipaddr, 0)) {
  524. return;
  525. }
  526. if(numPieces < fastSetSize) {
  527. fastSetSize = numPieces;
  528. }
  529. unsigned char tx[24];
  530. memcpy(tx, compact, 4);
  531. if((tx[0] & 0x80) == 0 || (tx[0] & 0x40) == 0) {
  532. tx[2] = 0x00;
  533. tx[3] = 0x00;
  534. } else {
  535. tx[3] = 0x00;
  536. }
  537. memcpy(tx+4, infoHash, 20);
  538. unsigned char x[20];
  539. MessageDigestHelper::digest(x, sizeof(x), MessageDigestContext::SHA1, tx, 24);
  540. while(fastSet.size() < fastSetSize) {
  541. for(size_t i = 0; i < 5 && fastSet.size() < fastSetSize; ++i) {
  542. size_t j = i*4;
  543. uint32_t ny;
  544. memcpy(&ny, x+j, 4);
  545. uint32_t y = ntohl(ny);
  546. size_t index = y%numPieces;
  547. if(std::find(fastSet.begin(), fastSet.end(), index) == fastSet.end()) {
  548. fastSet.push_back(index);
  549. }
  550. }
  551. unsigned char temp[20];
  552. MessageDigestHelper::digest(temp, sizeof(temp), MessageDigestContext::SHA1, x, sizeof(x));
  553. memcpy(x, temp, sizeof(x));
  554. }
  555. }
  556. std::string generatePeerId(const std::string& peerIdPrefix)
  557. {
  558. std::string peerId = peerIdPrefix;
  559. unsigned char buf[20];
  560. int len = 20-peerIdPrefix.size();
  561. if(len > 0) {
  562. util::generateRandomData(buf, len);
  563. peerId += std::string(&buf[0], &buf[len]);
  564. } if(peerId.size() > 20) {
  565. peerId.erase(20);
  566. }
  567. return peerId;
  568. }
  569. static std::string peerId;
  570. const std::string& generateStaticPeerId(const std::string& peerIdPrefix)
  571. {
  572. if(peerId.empty()) {
  573. peerId = generatePeerId(peerIdPrefix);
  574. }
  575. return peerId;
  576. }
  577. void setStaticPeerId(const std::string& newPeerId)
  578. {
  579. peerId = newPeerId;
  580. }
  581. // If PeerID is not generated, it is created with default peerIdPrefix
  582. // (aria2-).
  583. const unsigned char* getStaticPeerId()
  584. {
  585. if(peerId.empty()) {
  586. return
  587. reinterpret_cast<const unsigned char*>
  588. (generateStaticPeerId(DEFAULT_PEER_ID_PREFIX).data());
  589. } else {
  590. return reinterpret_cast<const unsigned char*>(peerId.data());
  591. }
  592. }
  593. uint8_t getId(const unsigned char* msg)
  594. {
  595. return msg[0];
  596. }
  597. uint32_t getIntParam(const unsigned char* msg, size_t pos)
  598. {
  599. uint32_t nParam;
  600. memcpy(&nParam, msg+pos, sizeof(nParam));
  601. return ntohl(nParam);
  602. }
  603. uint16_t getShortIntParam(const unsigned char* msg, size_t pos)
  604. {
  605. uint16_t nParam;
  606. memcpy(&nParam, msg+pos, sizeof(nParam));
  607. return ntohs(nParam);
  608. }
  609. void checkIndex(size_t index, size_t pieces)
  610. {
  611. if(!(index < pieces)) {
  612. throw DL_ABORT_EX(StringFormat("Invalid index: %lu",
  613. static_cast<unsigned long>(index)).str());
  614. }
  615. }
  616. void checkBegin(uint32_t begin, size_t pieceLength)
  617. {
  618. if(!(begin < pieceLength)) {
  619. throw DL_ABORT_EX(StringFormat("Invalid begin: %u", begin).str());
  620. }
  621. }
  622. void checkLength(size_t length)
  623. {
  624. if(length > MAX_BLOCK_LENGTH) {
  625. throw DL_ABORT_EX
  626. (StringFormat("Length too long: %lu > %uKB",
  627. static_cast<unsigned long>(length),
  628. MAX_BLOCK_LENGTH/1024).str());
  629. }
  630. if(length == 0) {
  631. throw DL_ABORT_EX
  632. (StringFormat("Invalid length: %lu",
  633. static_cast<unsigned long>(length)).str());
  634. }
  635. }
  636. void checkRange(uint32_t begin, size_t length, size_t pieceLength)
  637. {
  638. if(!(0 < length)) {
  639. throw DL_ABORT_EX
  640. (StringFormat("Invalid range: begin=%u, length=%lu",
  641. begin,
  642. static_cast<unsigned long>(length)).str());
  643. }
  644. uint32_t end = begin+length;
  645. if(!(end <= pieceLength)) {
  646. throw DL_ABORT_EX
  647. (StringFormat("Invalid range: begin=%u, length=%lu",
  648. begin,
  649. static_cast<unsigned long>(length)).str());
  650. }
  651. }
  652. void checkBitfield
  653. (const unsigned char* bitfield, size_t bitfieldLength, size_t pieces)
  654. {
  655. if(!(bitfieldLength == (pieces+7)/8)) {
  656. throw DL_ABORT_EX
  657. (StringFormat("Invalid bitfield length: %lu",
  658. static_cast<unsigned long>(bitfieldLength)).str());
  659. }
  660. // Check if last byte contains garbage set bit.
  661. if(bitfield[bitfieldLength-1]&~bitfield::lastByteMask(pieces)) {
  662. throw DL_ABORT_EX("Invalid bitfield");
  663. }
  664. }
  665. void setIntParam(unsigned char* dest, uint32_t param)
  666. {
  667. uint32_t nParam = htonl(param);
  668. memcpy(dest, &nParam, sizeof(nParam));
  669. }
  670. void setShortIntParam(unsigned char* dest, uint16_t param)
  671. {
  672. uint16_t nParam = htons(param);
  673. memcpy(dest, &nParam, sizeof(nParam));
  674. }
  675. void createPeerMessageString
  676. (unsigned char* msg, size_t msgLength, size_t payloadLength, uint8_t messageId)
  677. {
  678. assert(msgLength >= 5);
  679. memset(msg, 0, msgLength);
  680. setIntParam(msg, payloadLength);
  681. msg[4] = messageId;
  682. }
  683. bool createcompact
  684. (unsigned char* compact, const std::string& addr, uint16_t port)
  685. {
  686. struct addrinfo hints;
  687. struct addrinfo* res;
  688. memset(&hints, 0, sizeof(hints));
  689. hints.ai_family = AF_INET; // since compact peer format is ipv4 only.
  690. hints.ai_flags = AI_NUMERICHOST;
  691. if(getaddrinfo(addr.c_str(), 0, &hints, &res)) {
  692. return false;
  693. }
  694. struct sockaddr_in* in = reinterpret_cast<struct sockaddr_in*>(res->ai_addr);
  695. memcpy(compact, &(in->sin_addr.s_addr), sizeof(uint32_t));
  696. uint16_t port_nworder(htons(port));
  697. memcpy(compact+4, &port_nworder, sizeof(uint16_t));
  698. freeaddrinfo(res);
  699. return true;
  700. }
  701. std::pair<std::string, uint16_t> unpackcompact(const unsigned char* compact)
  702. {
  703. struct sockaddr_in in;
  704. memset(&in, 0, sizeof(in));
  705. #ifdef HAVE_SOCKADDR_IN_SIN_LEN
  706. // For netbsd
  707. in.sin_len = sizeof(in);
  708. #endif // HAVE_SOCKADDR_IN_SIN_LEN
  709. in.sin_family = AF_INET;
  710. memcpy(&(in.sin_addr.s_addr), compact, sizeof(uint32_t));
  711. in.sin_port = 0;
  712. char host[NI_MAXHOST];
  713. int s;
  714. s = getnameinfo(reinterpret_cast<const struct sockaddr*>(&in), sizeof(in),
  715. host, NI_MAXHOST, 0, NI_MAXSERV,
  716. NI_NUMERICHOST);
  717. if(s) {
  718. return std::pair<std::string, uint16_t>();
  719. }
  720. uint16_t port_nworder;
  721. memcpy(&port_nworder, compact+sizeof(uint32_t), sizeof(uint16_t));
  722. uint16_t port = ntohs(port_nworder);
  723. return std::pair<std::string, uint16_t>(host, port);
  724. }
  725. void assertPayloadLengthGreater
  726. (size_t threshold, size_t actual, const std::string& msgName)
  727. {
  728. if(actual <= threshold) {
  729. throw DL_ABORT_EX
  730. (StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE, msgName.c_str(), actual).str());
  731. }
  732. }
  733. void assertPayloadLengthEqual
  734. (size_t expected, size_t actual, const std::string& msgName)
  735. {
  736. if(expected != actual) {
  737. throw DL_ABORT_EX
  738. (StringFormat(EX_INVALID_PAYLOAD_SIZE, msgName.c_str(),
  739. actual, expected).str());
  740. }
  741. }
  742. void assertID
  743. (uint8_t expected, const unsigned char* data, const std::string& msgName)
  744. {
  745. uint8_t id = getId(data);
  746. if(expected != id) {
  747. throw DL_ABORT_EX
  748. (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, msgName.c_str(),
  749. expected).str());
  750. }
  751. }
  752. void generateRandomKey(unsigned char* key)
  753. {
  754. unsigned char bytes[40];
  755. util::generateRandomData(bytes, sizeof(bytes));
  756. MessageDigestHelper::digest(key, 20, MessageDigestContext::SHA1, bytes, sizeof(bytes));
  757. }
  758. } // namespace bittorrent
  759. } // namespace aria2