bittorrent_helper.cc 32 KB

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