bittorrent_helper.cc 33 KB

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