bittorrent_helper.cc 32 KB

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