bittorrent_helper.cc 34 KB

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