bittorrent_helper.cc 31 KB

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