bittorrent_helper.cc 32 KB

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