bittorrent_helper.cc 33 KB

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