bittorrent_helper.cc 31 KB

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