bittorrent_helper.cc 32 KB

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