bittorrent_helper.cc 30 KB

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