bittorrent_helper.cc 32 KB

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