bittorrent_helper.cc 28 KB

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