bittorrent_helper.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. namespace bittorrent {
  51. extern const std::string SINGLE;
  52. extern const std::string MULTI;
  53. extern const std::string BITTORRENT;
  54. void load(const std::string& torrentFile,
  55. const SharedHandle<DownloadContext>& ctx,
  56. const std::string& overrideName = "");
  57. void load(const std::string& torrentFile,
  58. const SharedHandle<DownloadContext>& ctx,
  59. const std::vector<std::string>& uris,
  60. const std::string& overrideName = "");
  61. void loadFromMemory(const unsigned char* content, size_t length,
  62. const SharedHandle<DownloadContext>& ctx,
  63. const std::string& defaultName,
  64. const std::string& overrideName = "");
  65. void loadFromMemory(const unsigned char* content, size_t length,
  66. const SharedHandle<DownloadContext>& ctx,
  67. const std::vector<std::string>& uris,
  68. const std::string& defaultName,
  69. const std::string& overrideName = "");
  70. void loadFromMemory(const std::string& context,
  71. const SharedHandle<DownloadContext>& ctx,
  72. const std::string& defaultName,
  73. const std::string& overrideName = "");
  74. void loadFromMemory(const std::string& context,
  75. const SharedHandle<DownloadContext>& ctx,
  76. const std::vector<std::string>& uris,
  77. const std::string& defaultName,
  78. const std::string& overrideName = "");
  79. // Parses BitTorrent Magnet URI and returns
  80. // SharedHandle<TorrentAttribute> which includes infoHash, name and
  81. // announceList. If parsing operation failed, an RecoverableException
  82. // will be thrown. infoHash and name are string and announceList is a
  83. // list of list of announce URI.
  84. //
  85. // magnet:?xt=urn:btih:<info-hash>&dn=<name>&tr=<tracker-url>
  86. // <info-hash> comes in 2 flavors: 40bytes hexadecimal ascii string,
  87. // or 32bytes Base32 encoded string.
  88. SharedHandle<TorrentAttribute> parseMagnet(const std::string& magnet);
  89. // Parses BitTorrent Magnet URI and set them in ctx as a
  90. // bittorrent::BITTORRENT attibute. If parsing operation failed, an
  91. // RecoverableException will be thrown.
  92. void loadMagnet
  93. (const std::string& magnet, const SharedHandle<DownloadContext>& ctx);
  94. // Generates Peer ID. BitTorrent specification says Peer ID is 20-byte
  95. // length. This function uses peerIdPrefix as a Peer ID and it is
  96. // less than 20bytes, random bytes are generated and appened to it. If
  97. // peerIdPrefix is larger than 20bytes, first 20bytes are used.
  98. std::string generatePeerId(const std::string& peerIdPrefix);
  99. // Generates Peer ID and stores it in static variable. This function
  100. // uses generatePeerId(peerIdPrefix) to produce Peer ID.
  101. const std::string& generateStaticPeerId(const std::string& peerIdPrefix);
  102. // Returns Peer ID statically stored by generateStaticPeerId(). If
  103. // Peer ID is not stored yet, this function calls
  104. // generateStaticPeerId("aria2-")
  105. const unsigned char* getStaticPeerId();
  106. // Set newPeerId as a static Peer ID. newPeerId must be 20-byte
  107. // length.
  108. void setStaticPeerId(const std::string& newPeerId);
  109. // Computes fast set index and stores them in fastset.
  110. void computeFastSet
  111. (std::vector<size_t>& fastSet, const std::string& ipaddr,
  112. size_t numPieces, const unsigned char* infoHash, size_t fastSetSize);
  113. // Writes the detailed information about torrent loaded in dctx.
  114. void print(std::ostream& o, const SharedHandle<DownloadContext>& dctx);
  115. SharedHandle<TorrentAttribute> getTorrentAttrs
  116. (const SharedHandle<DownloadContext>& dctx);
  117. // Returns the value associated with INFO_HASH key in BITTORRENT
  118. // attribute.
  119. const unsigned char*
  120. getInfoHash(const SharedHandle<DownloadContext>& downloadContext);
  121. std::string
  122. getInfoHashString(const SharedHandle<DownloadContext>& downloadContext);
  123. // Returns 4bytes unsigned integer located at offset pos. The integer
  124. // in msg is network byte order. This function converts it into host
  125. // byte order and returns it.
  126. uint32_t getIntParam(const unsigned char* msg, size_t pos);
  127. // Returns 2bytes unsigned integer located at offset pos. The integer
  128. // in msg is network byte order. This function converts it into host
  129. // byte order and returns it.
  130. uint16_t getShortIntParam(const unsigned char* msg, size_t pos);
  131. // Put param at location pointed by dest. param is converted into
  132. // network byte order.
  133. void setIntParam(unsigned char* dest, uint32_t param);
  134. // Put param at location pointed by dest. param is converted into
  135. // network byte order.
  136. void setShortIntParam(unsigned char* dest, uint16_t param);
  137. // Returns message ID located at first byte:msg[0]
  138. uint8_t getId(const unsigned char* msg);
  139. void checkIndex(size_t index, size_t pieces);
  140. void checkBegin(uint32_t begin, size_t pieceLength);
  141. void checkLength(size_t length);
  142. void checkRange(uint32_t begin, size_t length, size_t pieceLength);
  143. void checkBitfield
  144. (const unsigned char* bitfield, size_t bitfieldLength, size_t pieces);
  145. // Initialize msg with 0 and set payloadLength and messageId.
  146. void createPeerMessageString
  147. (unsigned char* msg, size_t msgLength, size_t payloadLength, uint8_t messageId);
  148. /**
  149. * Creates compact tracker format(6bytes for ipv4 address and port)
  150. * and stores the results in compact.
  151. * compact must be at least 6 bytes and pre-allocated.
  152. * Returns true if creation is successful, otherwise returns false.
  153. * The example of failure reason is that addr is not numbers-and-dots
  154. * notation.
  155. */
  156. bool createcompact
  157. (unsigned char* compact, const std::string& addr, uint16_t port);
  158. // Unpack compact into pair of IPv4 address and port.
  159. std::pair<std::string, uint16_t> unpackcompact(const unsigned char* compact);
  160. // Throws exception if threshold >= actual
  161. void assertPayloadLengthGreater
  162. (size_t threshold, size_t actual, const std::string& msgName);
  163. // Throws exception if expected != actual
  164. void assertPayloadLengthEqual
  165. (size_t expected, size_t actual, const std::string& msgName);
  166. // Throws exception if expected is not equal to id from data.
  167. void assertID
  168. (uint8_t expected, const unsigned char* data, const std::string& msgName);
  169. // Converts attrs into torrent data. This function does not guarantee
  170. // the returned string is valid torrent data.
  171. std::string metadata2Torrent
  172. (const std::string& metadata, const SharedHandle<TorrentAttribute>& attrs);
  173. // Constructs BitTorrent Magnet URI using attrs.
  174. std::string torrent2Magnet(const SharedHandle<TorrentAttribute>& attrs);
  175. template<typename OutputIterator>
  176. void extractPeer(const ValueBase* peerData, OutputIterator dest)
  177. {
  178. class PeerListValueBaseVisitor:public ValueBaseVisitor {
  179. private:
  180. OutputIterator dest_;
  181. public:
  182. PeerListValueBaseVisitor(OutputIterator dest):dest_(dest) {}
  183. virtual ~PeerListValueBaseVisitor() {}
  184. virtual void visit(const String& peerData)
  185. {
  186. size_t length = peerData.s().size();
  187. if(length%6 == 0) {
  188. const char* base = peerData.s().data();
  189. for(size_t i = 0; i < length; i += 6) {
  190. struct in_addr in;
  191. memcpy(&in.s_addr, base+i, sizeof(uint32_t));
  192. std::string ipaddr = inet_ntoa(in);
  193. uint16_t port_nworder;
  194. memcpy(&port_nworder, base+i+4, sizeof(uint16_t));
  195. uint16_t port = ntohs(port_nworder);
  196. *dest_ = SharedHandle<Peer>(new Peer(ipaddr, port));
  197. ++dest_;
  198. }
  199. }
  200. }
  201. virtual void visit(const Integer& v) {}
  202. virtual void visit(const List& peerData)
  203. {
  204. for(List::ValueType::const_iterator itr = peerData.begin(),
  205. eoi = peerData.end(); itr != eoi; ++itr) {
  206. const Dict* peerDict = asDict(*itr);
  207. if(!peerDict) {
  208. continue;
  209. }
  210. static const std::string IP = "ip";
  211. static const std::string PORT = "port";
  212. const String* ip = asString(peerDict->get(IP));
  213. const Integer* port = asInteger(peerDict->get(PORT));
  214. if(!ip || !port || !(0 < port->i() && port->i() < 65536)) {
  215. continue;
  216. }
  217. *dest_ = SharedHandle<Peer>(new Peer(ip->s(), port->i()));
  218. ++dest_;
  219. }
  220. }
  221. virtual void visit(const Dict& v) {}
  222. };
  223. if(peerData) {
  224. PeerListValueBaseVisitor visitor(dest);
  225. peerData->accept(visitor);
  226. }
  227. }
  228. template<typename OutputIterator>
  229. void extractPeer(const SharedHandle<ValueBase>& peerData, OutputIterator dest)
  230. {
  231. return extractPeer(peerData.get(), dest);
  232. }
  233. } // namespace bittorrent
  234. } // namespace aria2
  235. #endif // _D_BITTORRENT_HELPER_H_