bittorrent_helper.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. #ifndef D_BITTORRENT_HELPER_H
  36. #define D_BITTORRENT_HELPER_H
  37. #include "common.h"
  38. #include <cstring>
  39. #include <string>
  40. #include <vector>
  41. #include <utility>
  42. #include <memory>
  43. #include "TorrentAttribute.h"
  44. #include "a2netcompat.h"
  45. #include "Peer.h"
  46. #include "ValueBase.h"
  47. #include "util.h"
  48. #include "DownloadContext.h"
  49. #include "TimeA2.h"
  50. namespace aria2 {
  51. class DownloadContext;
  52. class Randomizer;
  53. class Option;
  54. namespace bittorrent {
  55. extern const std::string SINGLE;
  56. extern const std::string MULTI;
  57. void load(const std::string& torrentFile,
  58. const std::shared_ptr<DownloadContext>& ctx,
  59. const std::shared_ptr<Option>& option,
  60. const std::string& overrideName = "");
  61. void load(const std::string& torrentFile,
  62. const std::shared_ptr<DownloadContext>& ctx,
  63. const std::shared_ptr<Option>& option,
  64. const std::vector<std::string>& uris,
  65. const std::string& overrideName = "");
  66. void loadFromMemory(const unsigned char* content, size_t length,
  67. const std::shared_ptr<DownloadContext>& ctx,
  68. const std::shared_ptr<Option>& option,
  69. const std::string& defaultName,
  70. const std::string& overrideName = "");
  71. void loadFromMemory(const unsigned char* content, size_t length,
  72. const std::shared_ptr<DownloadContext>& ctx,
  73. const std::shared_ptr<Option>& option,
  74. const std::vector<std::string>& uris,
  75. const std::string& defaultName,
  76. const std::string& overrideName = "");
  77. void loadFromMemory(const std::string& context,
  78. const std::shared_ptr<DownloadContext>& ctx,
  79. const std::shared_ptr<Option>& option,
  80. const std::string& defaultName,
  81. const std::string& overrideName = "");
  82. void loadFromMemory(const std::string& context,
  83. const std::shared_ptr<DownloadContext>& ctx,
  84. const std::shared_ptr<Option>& option,
  85. const std::vector<std::string>& uris,
  86. const std::string& defaultName,
  87. const std::string& overrideName = "");
  88. void loadFromMemory(const ValueBase* torrent,
  89. const std::shared_ptr<DownloadContext>& ctx,
  90. const std::shared_ptr<Option>& option,
  91. const std::vector<std::string>& uris,
  92. const std::string& defaultName,
  93. const std::string& overrideName = "");
  94. // Parses BitTorrent Magnet URI and returns
  95. // std::unique_ptr<TorrentAttribute> which includes infoHash, name and
  96. // announceList. If parsing operation failed, an RecoverableException
  97. // will be thrown. infoHash and name are string and announceList is a
  98. // list of list of announce URI.
  99. //
  100. // magnet:?xt=urn:btih:<info-hash>&dn=<name>&tr=<tracker-url>
  101. // <info-hash> comes in 2 flavors: 40bytes hexadecimal ascii string,
  102. // or 32bytes Base32 encoded string.
  103. std::unique_ptr<TorrentAttribute> parseMagnet(const std::string& magnet);
  104. // Parses BitTorrent Magnet URI and set them in ctx as a
  105. // bittorrent::BITTORRENT attribute. If parsing operation failed, an
  106. // RecoverableException will be thrown.
  107. void loadMagnet(const std::string& magnet,
  108. const std::shared_ptr<DownloadContext>& ctx);
  109. // Generates Peer ID. BitTorrent specification says Peer ID is 20-byte
  110. // length. This function uses peerIdPrefix as a Peer ID and it is
  111. // less than 20bytes, random bytes are generated and appended to it. If
  112. // peerIdPrefix is larger than 20bytes, first 20bytes are used.
  113. std::string generatePeerId(const std::string& peerIdPrefix);
  114. // Generates Peer ID and stores it in static variable. This function
  115. // uses generatePeerId(peerIdPrefix) to produce Peer ID.
  116. const std::string& generateStaticPeerId(const std::string& peerIdPrefix);
  117. const std::string& generateStaticPeerAgent(const std::string& peerAgent);
  118. // Returns Peer ID statically stored by generateStaticPeerId(). If
  119. // Peer ID is not stored yet, this function calls
  120. // generateStaticPeerId("aria2-")
  121. const unsigned char* getStaticPeerId();
  122. const std::string& getStaticPeerAgent();
  123. // Set newPeerId as a static Peer ID. newPeerId must be 20-byte
  124. // length.
  125. void setStaticPeerId(const std::string& newPeerId);
  126. void setStaticPeerAgent(const std::string& newPeerAgent);
  127. // Computes fast set index and returns them.
  128. std::vector<size_t> computeFastSet(const std::string& ipaddr, size_t numPieces,
  129. const unsigned char* infoHash,
  130. size_t fastSetSize);
  131. // Make sure that don't receive return value into std::shared_ptr.
  132. TorrentAttribute* getTorrentAttrs(DownloadContext* dctx);
  133. TorrentAttribute* getTorrentAttrs(const std::shared_ptr<DownloadContext>& dctx);
  134. // Returns the value associated with INFO_HASH key in BITTORRENT
  135. // attribute.
  136. const unsigned char* getInfoHash(DownloadContext* downloadContext);
  137. const unsigned char*
  138. getInfoHash(const std::shared_ptr<DownloadContext>& downloadContext);
  139. std::string getInfoHashString(DownloadContext* downloadContext);
  140. std::string
  141. getInfoHashString(const std::shared_ptr<DownloadContext>& downloadContext);
  142. // Returns 8bytes unsigned integer located at offset pos. The integer
  143. // in msg is network byte order. This function converts it into host
  144. // byte order and returns it.
  145. uint64_t getLLIntParam(const unsigned char* msg, size_t pos);
  146. // Returns 4bytes unsigned integer located at offset pos. The integer
  147. // in msg is network byte order. This function converts it into host
  148. // byte order and returns it.
  149. uint32_t getIntParam(const unsigned char* msg, size_t pos);
  150. // Returns 2bytes unsigned integer located at offset pos. The integer
  151. // in msg is network byte order. This function converts it into host
  152. // byte order and returns it.
  153. uint16_t getShortIntParam(const unsigned char* msg, size_t pos);
  154. // Put param at location pointed by dest. param is converted into
  155. // network byte order.
  156. void setLLIntParam(unsigned char* dest, uint64_t param);
  157. // Put param at location pointed by dest. param is converted into
  158. // network byte order.
  159. void setIntParam(unsigned char* dest, uint32_t param);
  160. // Put param at location pointed by dest. param is converted into
  161. // network byte order.
  162. void setShortIntParam(unsigned char* dest, uint16_t param);
  163. // Returns message ID located at first byte:msg[0]
  164. uint8_t getId(const unsigned char* msg);
  165. void checkIndex(size_t index, size_t pieces);
  166. void checkBegin(int32_t begin, int32_t pieceLength);
  167. void checkLength(int32_t length);
  168. void checkRange(int32_t begin, int32_t length, int32_t pieceLength);
  169. void checkBitfield(const unsigned char* bitfield, size_t bitfieldLength,
  170. size_t pieces);
  171. // Initialize msg with 0 and set payloadLength and messageId.
  172. void createPeerMessageString(unsigned char* msg, size_t msgLength,
  173. size_t payloadLength, uint8_t messageId);
  174. /**
  175. * Creates compact form(packed addresss + 2bytes port) and stores the
  176. * results in compact. This function looks addr and if it is IPv4
  177. * address, it stores 6bytes in compact and if it is IPv6, it stores
  178. * 18bytes in compact. So compact must be at least 18 bytes and
  179. * pre-allocated. Returns the number of written bytes; for IPv4
  180. * address, it is 6 and for IPv6, it is 18. On failure, returns 0.
  181. */
  182. size_t packcompact(unsigned char* compact, const std::string& addr,
  183. uint16_t port);
  184. /**
  185. * Unpack packed address and port in compact and returns address and
  186. * port pair. family must be AF_INET or AF_INET6. If family is
  187. * AF_INET, first 6 bytes from compact is used. If family is
  188. * AF_INET6, first 18 bytes from compact is used. On failure, returns
  189. * std::pair<std::string, uint16_t>().
  190. */
  191. std::pair<std::string, uint16_t> unpackcompact(const unsigned char* compact,
  192. int family);
  193. // Throws exception if threshold >= actual
  194. void assertPayloadLengthGreater(size_t threshold, size_t actual,
  195. const char* msgName);
  196. // Throws exception if expected != actual
  197. void assertPayloadLengthEqual(size_t expected, size_t actual,
  198. const char* msgName);
  199. // Throws exception if expected is not equal to id from data.
  200. void assertID(uint8_t expected, const unsigned char* data, const char* msgName);
  201. // Converts attrs into torrent data. This function does not guarantee
  202. // the returned string is valid torrent data.
  203. std::string metadata2Torrent(const std::string& metadata,
  204. const TorrentAttribute* attrs);
  205. // Constructs BitTorrent Magnet URI using attrs.
  206. std::string torrent2Magnet(const TorrentAttribute* attrs);
  207. // Removes announce URI in uris from attrs. If uris contains '*', all
  208. // announce URIs are removed.
  209. void removeAnnounceUri(TorrentAttribute* attrs,
  210. const std::vector<std::string>& uris);
  211. // Adds announce URI in uris to attrs. Each URI in uris creates its
  212. // own tier.
  213. void addAnnounceUri(TorrentAttribute* attrs,
  214. const std::vector<std::string>& uris);
  215. // This helper function uses 2 option values: PREF_BT_TRACKER and
  216. // PREF_BT_EXCLUDE_TRACKER. First, the value of
  217. // PREF_BT_EXCLUDE_TRACKER is converted to std::vector<std::string>
  218. // and call removeAnnounceUri(). Then the value of PREF_BT_TRACKER is
  219. // converted to std::vector<std::string> and call addAnnounceUri().
  220. void adjustAnnounceUri(TorrentAttribute* attrs,
  221. const std::shared_ptr<Option>& option);
  222. template <typename OutputIterator>
  223. void extractPeer(const ValueBase* peerData, int family, OutputIterator dest)
  224. {
  225. class PeerListValueBaseVisitor : public ValueBaseVisitor {
  226. private:
  227. OutputIterator dest_;
  228. int family_;
  229. public:
  230. PeerListValueBaseVisitor(OutputIterator dest, int family)
  231. : dest_(dest), family_(family)
  232. {
  233. }
  234. virtual ~PeerListValueBaseVisitor() = default;
  235. virtual void visit(const String& peerData) CXX11_OVERRIDE
  236. {
  237. int unit = family_ == AF_INET ? 6 : 18;
  238. size_t length = peerData.s().size();
  239. if (length % unit == 0) {
  240. const unsigned char* base =
  241. reinterpret_cast<const unsigned char*>(peerData.s().data());
  242. const unsigned char* end = base + length;
  243. for (; base != end; base += unit) {
  244. std::pair<std::string, uint16_t> p = unpackcompact(base, family_);
  245. if (p.first.empty()) {
  246. continue;
  247. }
  248. *dest_++ = std::make_shared<Peer>(p.first, p.second);
  249. }
  250. }
  251. }
  252. virtual void visit(const Integer& v) CXX11_OVERRIDE {}
  253. virtual void visit(const Bool& v) CXX11_OVERRIDE {}
  254. virtual void visit(const Null& v) CXX11_OVERRIDE {}
  255. virtual void visit(const List& peerData) CXX11_OVERRIDE
  256. {
  257. for (auto& elem : peerData) {
  258. const Dict* peerDict = downcast<Dict>(elem);
  259. if (!peerDict) {
  260. continue;
  261. }
  262. static const std::string IP = "ip";
  263. static const std::string PORT = "port";
  264. const String* ip = downcast<String>(peerDict->get(IP));
  265. const Integer* port = downcast<Integer>(peerDict->get(PORT));
  266. if (!ip || !port || !(0 < port->i() && port->i() < 65536)) {
  267. continue;
  268. }
  269. *dest_ = std::make_shared<Peer>(ip->s(), port->i());
  270. ++dest_;
  271. }
  272. }
  273. virtual void visit(const Dict& v) CXX11_OVERRIDE {}
  274. };
  275. if (peerData) {
  276. PeerListValueBaseVisitor visitor(dest, family);
  277. peerData->accept(visitor);
  278. }
  279. }
  280. int getCompactLength(int family);
  281. // Returns textual representation of the |mode|.
  282. const char* getModeString(BtFileMode mode);
  283. // Writes the detailed information about torrent loaded in dctx.
  284. template <typename Output>
  285. void print(Output& o, const std::shared_ptr<DownloadContext>& dctx)
  286. {
  287. TorrentAttribute* torrentAttrs = getTorrentAttrs(dctx);
  288. o.write("*** BitTorrent File Information ***\n");
  289. if (!torrentAttrs->comment.empty()) {
  290. o.printf("Comment: %s\n", torrentAttrs->comment.c_str());
  291. }
  292. if (torrentAttrs->creationDate) {
  293. o.printf("Creation Date: %s\n",
  294. Time(torrentAttrs->creationDate).toHTTPDate().c_str());
  295. }
  296. if (!torrentAttrs->createdBy.empty()) {
  297. o.printf("Created By: %s\n", torrentAttrs->createdBy.c_str());
  298. }
  299. o.printf("Mode: %s\n", getModeString(torrentAttrs->mode));
  300. o.write("Announce:\n");
  301. for (std::vector<std::vector<std::string>>::const_iterator
  302. tierIter = torrentAttrs->announceList.begin(),
  303. eoi = torrentAttrs->announceList.end();
  304. tierIter != eoi; ++tierIter) {
  305. for (auto& elem : *tierIter) {
  306. o.printf(" %s", elem.c_str());
  307. }
  308. o.write("\n");
  309. }
  310. o.printf("Info Hash: %s\n", util::toHex(torrentAttrs->infoHash).c_str());
  311. o.printf("Piece Length: %sB\n",
  312. util::abbrevSize(dctx->getPieceLength()).c_str());
  313. o.printf("The Number of Pieces: %lu\n",
  314. static_cast<unsigned long>(dctx->getNumPieces()));
  315. o.printf("Total Length: %sB (%s)\n",
  316. util::abbrevSize(dctx->getTotalLength()).c_str(),
  317. util::uitos(dctx->getTotalLength(), true).c_str());
  318. if (!torrentAttrs->urlList.empty()) {
  319. o.write("URL List:\n");
  320. for (std::vector<std::string>::const_iterator
  321. i = torrentAttrs->urlList.begin(),
  322. eoi = torrentAttrs->urlList.end();
  323. i != eoi; ++i) {
  324. o.printf(" %s\n", (*i).c_str());
  325. }
  326. }
  327. if (!torrentAttrs->nodes.empty()) {
  328. o.write("Nodes:\n");
  329. for (auto& p : torrentAttrs->nodes) {
  330. o.printf(" %s:%u\n", p.first.c_str(), p.second);
  331. }
  332. }
  333. o.printf("Name: %s\n", torrentAttrs->name.c_str());
  334. o.printf("Magnet URI: %s\n", torrent2Magnet(torrentAttrs).c_str());
  335. util::toStream(dctx->getFileEntries().begin(), dctx->getFileEntries().end(),
  336. o);
  337. }
  338. } // namespace bittorrent
  339. } // namespace aria2
  340. #endif // D_BITTORRENT_HELPER_H