bittorrent_helper.h 14 KB

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