bittorrent_helper.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 "SharedHandle.h"
  43. #include "TorrentAttribute.h"
  44. #include "a2netcompat.h"
  45. #include "Peer.h"
  46. #include "ValueBase.h"
  47. namespace aria2 {
  48. class DownloadContext;
  49. class Randomizer;
  50. class Option;
  51. namespace bittorrent {
  52. extern const std::string SINGLE;
  53. extern const std::string MULTI;
  54. extern const std::string BITTORRENT;
  55. void load(const std::string& torrentFile,
  56. const SharedHandle<DownloadContext>& ctx,
  57. const SharedHandle<Option>& option,
  58. const std::string& overrideName = "");
  59. void load(const std::string& torrentFile,
  60. const SharedHandle<DownloadContext>& ctx,
  61. const SharedHandle<Option>& option,
  62. const std::vector<std::string>& uris,
  63. const std::string& overrideName = "");
  64. void loadFromMemory(const unsigned char* content, size_t length,
  65. const SharedHandle<DownloadContext>& ctx,
  66. const SharedHandle<Option>& option,
  67. const std::string& defaultName,
  68. const std::string& overrideName = "");
  69. void loadFromMemory(const unsigned char* content, size_t length,
  70. const SharedHandle<DownloadContext>& ctx,
  71. const SharedHandle<Option>& option,
  72. const std::vector<std::string>& uris,
  73. const std::string& defaultName,
  74. const std::string& overrideName = "");
  75. void loadFromMemory(const std::string& context,
  76. const SharedHandle<DownloadContext>& ctx,
  77. const SharedHandle<Option>& option,
  78. const std::string& defaultName,
  79. const std::string& overrideName = "");
  80. void loadFromMemory(const std::string& context,
  81. const SharedHandle<DownloadContext>& ctx,
  82. const SharedHandle<Option>& option,
  83. const std::vector<std::string>& uris,
  84. const std::string& defaultName,
  85. const std::string& overrideName = "");
  86. // Parses BitTorrent Magnet URI and returns
  87. // SharedHandle<TorrentAttribute> which includes infoHash, name and
  88. // announceList. If parsing operation failed, an RecoverableException
  89. // will be thrown. infoHash and name are string and announceList is a
  90. // list of list of announce URI.
  91. //
  92. // magnet:?xt=urn:btih:<info-hash>&dn=<name>&tr=<tracker-url>
  93. // <info-hash> comes in 2 flavors: 40bytes hexadecimal ascii string,
  94. // or 32bytes Base32 encoded string.
  95. SharedHandle<TorrentAttribute> parseMagnet(const std::string& magnet);
  96. // Parses BitTorrent Magnet URI and set them in ctx as a
  97. // bittorrent::BITTORRENT attibute. If parsing operation failed, an
  98. // RecoverableException will be thrown.
  99. void loadMagnet
  100. (const std::string& magnet, const SharedHandle<DownloadContext>& ctx);
  101. // Generates Peer ID. BitTorrent specification says Peer ID is 20-byte
  102. // length. This function uses peerIdPrefix as a Peer ID and it is
  103. // less than 20bytes, random bytes are generated and appened to it. If
  104. // peerIdPrefix is larger than 20bytes, first 20bytes are used.
  105. std::string generatePeerId(const std::string& peerIdPrefix);
  106. // Generates Peer ID and stores it in static variable. This function
  107. // uses generatePeerId(peerIdPrefix) to produce Peer ID.
  108. const std::string& generateStaticPeerId(const std::string& peerIdPrefix);
  109. // Returns Peer ID statically stored by generateStaticPeerId(). If
  110. // Peer ID is not stored yet, this function calls
  111. // generateStaticPeerId("aria2-")
  112. const unsigned char* getStaticPeerId();
  113. // Set newPeerId as a static Peer ID. newPeerId must be 20-byte
  114. // length.
  115. void setStaticPeerId(const std::string& newPeerId);
  116. // Computes fast set index and stores them in fastset.
  117. void computeFastSet
  118. (std::vector<size_t>& fastSet, const std::string& ipaddr,
  119. size_t numPieces, const unsigned char* infoHash, size_t fastSetSize);
  120. // Writes the detailed information about torrent loaded in dctx.
  121. void print(std::ostream& o, const SharedHandle<DownloadContext>& dctx);
  122. SharedHandle<TorrentAttribute> getTorrentAttrs
  123. (const SharedHandle<DownloadContext>& dctx);
  124. // Returns the value associated with INFO_HASH key in BITTORRENT
  125. // attribute.
  126. const unsigned char*
  127. getInfoHash(const SharedHandle<DownloadContext>& downloadContext);
  128. std::string
  129. getInfoHashString(const SharedHandle<DownloadContext>& downloadContext);
  130. // Returns 4bytes unsigned integer located at offset pos. The integer
  131. // in msg is network byte order. This function converts it into host
  132. // byte order and returns it.
  133. uint32_t getIntParam(const unsigned char* msg, size_t pos);
  134. // Returns 2bytes unsigned integer located at offset pos. The integer
  135. // in msg is network byte order. This function converts it into host
  136. // byte order and returns it.
  137. uint16_t getShortIntParam(const unsigned char* msg, size_t pos);
  138. // Put param at location pointed by dest. param is converted into
  139. // network byte order.
  140. void setIntParam(unsigned char* dest, uint32_t param);
  141. // Put param at location pointed by dest. param is converted into
  142. // network byte order.
  143. void setShortIntParam(unsigned char* dest, uint16_t param);
  144. // Returns message ID located at first byte:msg[0]
  145. uint8_t getId(const unsigned char* msg);
  146. void checkIndex(size_t index, size_t pieces);
  147. void checkBegin(uint32_t begin, size_t pieceLength);
  148. void checkLength(size_t length);
  149. void checkRange(uint32_t begin, size_t length, size_t pieceLength);
  150. void checkBitfield
  151. (const unsigned char* bitfield, size_t bitfieldLength, size_t pieces);
  152. // Initialize msg with 0 and set payloadLength and messageId.
  153. void createPeerMessageString
  154. (unsigned char* msg, size_t msgLength, size_t payloadLength, uint8_t messageId);
  155. /**
  156. * Creates compact form(packed addresss + 2bytes port) and stores the
  157. * results in compact. This function looks addr and if it is IPv4
  158. * address, it stores 6bytes in compact and if it is IPv6, it stores
  159. * 18bytes in compact. So compact must be at least 18 bytes and
  160. * pre-allocated. Returns the number of written bytes; for IPv4
  161. * address, it is 6 and for IPv6, it is 18. On failure, returns 0.
  162. */
  163. int packcompact
  164. (unsigned char* compact, const std::string& addr, uint16_t port);
  165. /**
  166. * Unpack packed address and port in compact and returns address and
  167. * port pair. family must be AF_INET or AF_INET6. If family is
  168. * AF_INET, first 6 bytes from compact is used. If family is
  169. * AF_INET6, first 18 bytes from compact is used. On failure, returns
  170. * std::pair<std::string, uint16_t>().
  171. */
  172. std::pair<std::string, uint16_t>
  173. unpackcompact(const unsigned char* compact, int family);
  174. // Throws exception if threshold >= actual
  175. void assertPayloadLengthGreater
  176. (size_t threshold, size_t actual, const std::string& msgName);
  177. // Throws exception if expected != actual
  178. void assertPayloadLengthEqual
  179. (size_t expected, size_t actual, const std::string& msgName);
  180. // Throws exception if expected is not equal to id from data.
  181. void assertID
  182. (uint8_t expected, const unsigned char* data, const std::string& msgName);
  183. // Converts attrs into torrent data. This function does not guarantee
  184. // the returned string is valid torrent data.
  185. std::string metadata2Torrent
  186. (const std::string& metadata, const SharedHandle<TorrentAttribute>& attrs);
  187. // Constructs BitTorrent Magnet URI using attrs.
  188. std::string torrent2Magnet(const SharedHandle<TorrentAttribute>& attrs);
  189. // Removes announce URI in uris from attrs. If uris contains '*', all
  190. // announce URIs are removed.
  191. void removeAnnounceUri
  192. (const SharedHandle<TorrentAttribute>& attrs,
  193. const std::vector<std::string>& uris);
  194. // Adds announce URI in uris to attrs. Each URI in uris creates its
  195. // own tier.
  196. void addAnnounceUri
  197. (const SharedHandle<TorrentAttribute>& attrs,
  198. const std::vector<std::string>& uris);
  199. // This helper function uses 2 option values: PREF_BT_TRACKER and
  200. // PREF_BT_EXCLUDE_TRACKER. First, the value of
  201. // PREF_BT_EXCLUDE_TRACKER is converted to std::vector<std::string>
  202. // and call removeAnnounceUri(). Then the value of PREF_BT_TRACKER is
  203. // converted to std::vector<std::string> and call addAnnounceUri().
  204. void adjustAnnounceUri
  205. (const SharedHandle<TorrentAttribute>& attrs,
  206. const SharedHandle<Option>& option);
  207. template<typename OutputIterator>
  208. void extractPeer(const ValueBase* peerData, int family, OutputIterator dest)
  209. {
  210. class PeerListValueBaseVisitor:public ValueBaseVisitor {
  211. private:
  212. OutputIterator dest_;
  213. int family_;
  214. public:
  215. PeerListValueBaseVisitor(OutputIterator dest, int family):
  216. dest_(dest),
  217. family_(family) {}
  218. virtual ~PeerListValueBaseVisitor() {}
  219. virtual void visit(const String& peerData)
  220. {
  221. int unit = family_ == AF_INET?6:18;
  222. size_t length = peerData.s().size();
  223. if(length%unit == 0) {
  224. const unsigned char* base =
  225. reinterpret_cast<const unsigned char*>(peerData.s().data());
  226. const unsigned char* end = base+length;
  227. for(; base != end; base += unit) {
  228. std::pair<std::string, uint16_t> p = unpackcompact(base, family_);
  229. if(p.first.empty()) {
  230. continue;
  231. }
  232. *dest_++ = SharedHandle<Peer>(new Peer(p.first, p.second));
  233. }
  234. }
  235. }
  236. virtual void visit(const Integer& v) {}
  237. virtual void visit(const Bool& v) {}
  238. virtual void visit(const Null& v) {}
  239. virtual void visit(const List& peerData)
  240. {
  241. for(List::ValueType::const_iterator itr = peerData.begin(),
  242. eoi = peerData.end(); itr != eoi; ++itr) {
  243. const Dict* peerDict = asDict(*itr);
  244. if(!peerDict) {
  245. continue;
  246. }
  247. static const std::string IP = "ip";
  248. static const std::string PORT = "port";
  249. const String* ip = asString(peerDict->get(IP));
  250. const Integer* port = asInteger(peerDict->get(PORT));
  251. if(!ip || !port || !(0 < port->i() && port->i() < 65536)) {
  252. continue;
  253. }
  254. *dest_ = SharedHandle<Peer>(new Peer(ip->s(), port->i()));
  255. ++dest_;
  256. }
  257. }
  258. virtual void visit(const Dict& v) {}
  259. };
  260. if(peerData) {
  261. PeerListValueBaseVisitor visitor(dest, family);
  262. peerData->accept(visitor);
  263. }
  264. }
  265. template<typename OutputIterator>
  266. void extractPeer
  267. (const SharedHandle<ValueBase>& peerData, int family, OutputIterator dest)
  268. {
  269. return extractPeer(peerData.get(), family, dest);
  270. }
  271. int getCompactLength(int family);
  272. } // namespace bittorrent
  273. } // namespace aria2
  274. #endif // D_BITTORRENT_HELPER_H