bittorrent_helper.cc 33 KB

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