bittorrent_helper.cc 32 KB

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