bittorrent_helper.cc 32 KB

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