bittorrent_helper.cc 29 KB

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