Destination.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #ifndef DESTINATION_H__
  2. #define DESTINATION_H__
  3. #include <thread>
  4. #include <mutex>
  5. #include <memory>
  6. #include <map>
  7. #include <set>
  8. #include <string>
  9. #include <functional>
  10. #ifdef I2LUA
  11. #include <future>
  12. #endif
  13. #include <boost/asio.hpp>
  14. #include "Identity.h"
  15. #include "TunnelPool.h"
  16. #include "Crypto.h"
  17. #include "LeaseSet.h"
  18. #include "Garlic.h"
  19. #include "NetDb.hpp"
  20. #include "Streaming.h"
  21. #include "Datagram.h"
  22. namespace i2p
  23. {
  24. namespace client
  25. {
  26. const uint8_t PROTOCOL_TYPE_STREAMING = 6;
  27. const uint8_t PROTOCOL_TYPE_DATAGRAM = 17;
  28. const uint8_t PROTOCOL_TYPE_RAW = 18;
  29. const int PUBLISH_CONFIRMATION_TIMEOUT = 5; // in seconds
  30. const int PUBLISH_VERIFICATION_TIMEOUT = 10; // in seconds after successful publish
  31. const int PUBLISH_MIN_INTERVAL = 20; // in seconds
  32. const int PUBLISH_REGULAR_VERIFICATION_INTERNAL = 100; // in seconds periodically
  33. const int LEASESET_REQUEST_TIMEOUT = 5; // in seconds
  34. const int MAX_LEASESET_REQUEST_TIMEOUT = 40; // in seconds
  35. const int DESTINATION_CLEANUP_TIMEOUT = 3; // in minutes
  36. const unsigned int MAX_NUM_FLOODFILLS_PER_REQUEST = 7;
  37. // I2CP
  38. const char I2CP_PARAM_INBOUND_TUNNEL_LENGTH[] = "inbound.length";
  39. const int DEFAULT_INBOUND_TUNNEL_LENGTH = 3;
  40. const char I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH[] = "outbound.length";
  41. const int DEFAULT_OUTBOUND_TUNNEL_LENGTH = 3;
  42. const char I2CP_PARAM_INBOUND_TUNNELS_QUANTITY[] = "inbound.quantity";
  43. const int DEFAULT_INBOUND_TUNNELS_QUANTITY = 5;
  44. const char I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY[] = "outbound.quantity";
  45. const int DEFAULT_OUTBOUND_TUNNELS_QUANTITY = 5;
  46. const char I2CP_PARAM_EXPLICIT_PEERS[] = "explicitPeers";
  47. const int STREAM_REQUEST_TIMEOUT = 60; //in seconds
  48. const char I2CP_PARAM_TAGS_TO_SEND[] = "crypto.tagsToSend";
  49. const int DEFAULT_TAGS_TO_SEND = 40;
  50. const char I2CP_PARAM_INBOUND_NICKNAME[] = "inbound.nickname";
  51. const char I2CP_PARAM_OUTBOUND_NICKNAME[] = "outbound.nickname";
  52. const char I2CP_PARAM_LEASESET_TYPE[] = "i2cp.leaseSetType";
  53. const int DEFAULT_LEASESET_TYPE = 1;
  54. const char I2CP_PARAM_LEASESET_ENCRYPTION_TYPE[] = "i2cp.leaseSetEncType";
  55. const char I2CP_PARAM_LEASESET_PRIV_KEY[] = "i2cp.leaseSetPrivKey"; // PSK decryption key, base64
  56. const char I2CP_PARAM_LEASESET_AUTH_TYPE[] = "i2cp.leaseSetAuthType";
  57. const char I2CP_PARAM_LEASESET_CLIENT_DH[] = "i2cp.leaseSetClient.dh"; // group of i2cp.leaseSetClient.dh.nnn
  58. const char I2CP_PARAM_LEASESET_CLIENT_PSK[] = "i2cp.leaseSetClient.psk"; // group of i2cp.leaseSetClient.psk.nnn
  59. // latency
  60. const char I2CP_PARAM_MIN_TUNNEL_LATENCY[] = "latency.min";
  61. const int DEFAULT_MIN_TUNNEL_LATENCY = 0;
  62. const char I2CP_PARAM_MAX_TUNNEL_LATENCY[] = "latency.max";
  63. const int DEFAULT_MAX_TUNNEL_LATENCY = 0;
  64. // streaming
  65. const char I2CP_PARAM_STREAMING_INITIAL_ACK_DELAY[] = "i2p.streaming.initialAckDelay";
  66. const int DEFAULT_INITIAL_ACK_DELAY = 200; // milliseconds
  67. typedef std::function<void (std::shared_ptr<i2p::stream::Stream> stream)> StreamRequestComplete;
  68. class LeaseSetDestination: public i2p::garlic::GarlicDestination,
  69. public std::enable_shared_from_this<LeaseSetDestination>
  70. {
  71. typedef std::function<void (std::shared_ptr<i2p::data::LeaseSet> leaseSet)> RequestComplete;
  72. // leaseSet = nullptr means not found
  73. struct LeaseSetRequest
  74. {
  75. LeaseSetRequest (boost::asio::io_service& service): requestTime (0), requestTimeoutTimer (service) {};
  76. std::set<i2p::data::IdentHash> excluded;
  77. uint64_t requestTime;
  78. boost::asio::deadline_timer requestTimeoutTimer;
  79. std::list<RequestComplete> requestComplete;
  80. std::shared_ptr<i2p::tunnel::OutboundTunnel> outboundTunnel;
  81. std::shared_ptr<i2p::tunnel::InboundTunnel> replyTunnel;
  82. std::shared_ptr<const i2p::data::BlindedPublicKey> requestedBlindedKey; // for encrypted LeaseSet2 only
  83. void Complete (std::shared_ptr<i2p::data::LeaseSet> ls)
  84. {
  85. for (auto& it: requestComplete) it (ls);
  86. requestComplete.clear ();
  87. }
  88. };
  89. public:
  90. LeaseSetDestination (bool isPublic, const std::map<std::string, std::string> * params = nullptr);
  91. ~LeaseSetDestination ();
  92. const std::string& GetNickname () const { return m_Nickname; };
  93. virtual bool Start ();
  94. virtual bool Stop ();
  95. /** i2cp reconfigure */
  96. virtual bool Reconfigure(std::map<std::string, std::string> i2cpOpts);
  97. bool IsRunning () const { return m_IsRunning; };
  98. boost::asio::io_service& GetService () { return m_Service; };
  99. std::shared_ptr<i2p::tunnel::TunnelPool> GetTunnelPool () { return m_Pool; };
  100. bool IsReady () const { return m_LeaseSet && !m_LeaseSet->IsExpired () && m_Pool->GetOutboundTunnels ().size () > 0; };
  101. std::shared_ptr<i2p::data::LeaseSet> FindLeaseSet (const i2p::data::IdentHash& ident);
  102. bool RequestDestination (const i2p::data::IdentHash& dest, RequestComplete requestComplete = nullptr);
  103. bool RequestDestinationWithEncryptedLeaseSet (std::shared_ptr<const i2p::data::BlindedPublicKey> dest, RequestComplete requestComplete = nullptr);
  104. void CancelDestinationRequest (const i2p::data::IdentHash& dest, bool notify = true);
  105. void CancelDestinationRequestWithEncryptedLeaseSet (std::shared_ptr<const i2p::data::BlindedPublicKey> dest, bool notify = true);
  106. // implements GarlicDestination
  107. std::shared_ptr<const i2p::data::LocalLeaseSet> GetLeaseSet ();
  108. std::shared_ptr<i2p::tunnel::TunnelPool> GetTunnelPool () const { return m_Pool; }
  109. void HandleI2NPMessage (const uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from);
  110. // override GarlicDestination
  111. bool SubmitSessionKey (const uint8_t * key, const uint8_t * tag);
  112. void ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg);
  113. void ProcessDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg);
  114. void SetLeaseSetUpdated ();
  115. protected:
  116. void SetLeaseSet (std::shared_ptr<const i2p::data::LocalLeaseSet> newLeaseSet);
  117. int GetLeaseSetType () const { return m_LeaseSetType; };
  118. void SetLeaseSetType (int leaseSetType) { m_LeaseSetType = leaseSetType; };
  119. bool IsPublic () const { return m_IsPublic; };
  120. virtual void CleanupDestination () {}; // additional clean up in derived classes
  121. // I2CP
  122. virtual void HandleDataMessage (const uint8_t * buf, size_t len) = 0;
  123. virtual void CreateNewLeaseSet (std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> > tunnels) = 0;
  124. private:
  125. void Run ();
  126. void UpdateLeaseSet ();
  127. std::shared_ptr<const i2p::data::LocalLeaseSet> GetLeaseSetMt ();
  128. void Publish ();
  129. void HandlePublishConfirmationTimer (const boost::system::error_code& ecode);
  130. void HandlePublishVerificationTimer (const boost::system::error_code& ecode);
  131. void HandlePublishDelayTimer (const boost::system::error_code& ecode);
  132. void HandleDatabaseStoreMessage (const uint8_t * buf, size_t len);
  133. void HandleDatabaseSearchReplyMessage (const uint8_t * buf, size_t len);
  134. void HandleDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg);
  135. void RequestLeaseSet (const i2p::data::IdentHash& dest, RequestComplete requestComplete, std::shared_ptr<const i2p::data::BlindedPublicKey> requestedBlindedKey = nullptr);
  136. bool SendLeaseSetRequest (const i2p::data::IdentHash& dest, std::shared_ptr<const i2p::data::RouterInfo> nextFloodfill, std::shared_ptr<LeaseSetRequest> request);
  137. void HandleRequestTimoutTimer (const boost::system::error_code& ecode, const i2p::data::IdentHash& dest);
  138. void HandleCleanupTimer (const boost::system::error_code& ecode);
  139. void CleanupRemoteLeaseSets ();
  140. private:
  141. volatile bool m_IsRunning;
  142. std::thread * m_Thread;
  143. boost::asio::io_service m_Service;
  144. mutable std::mutex m_RemoteLeaseSetsMutex;
  145. std::map<i2p::data::IdentHash, std::shared_ptr<i2p::data::LeaseSet> > m_RemoteLeaseSets;
  146. std::map<i2p::data::IdentHash, std::shared_ptr<LeaseSetRequest> > m_LeaseSetRequests;
  147. std::shared_ptr<i2p::tunnel::TunnelPool> m_Pool;
  148. std::mutex m_LeaseSetMutex;
  149. std::shared_ptr<const i2p::data::LocalLeaseSet> m_LeaseSet;
  150. bool m_IsPublic;
  151. uint32_t m_PublishReplyToken;
  152. uint64_t m_LastSubmissionTime; // in seconds
  153. std::set<i2p::data::IdentHash> m_ExcludedFloodfills; // for publishing
  154. boost::asio::deadline_timer m_PublishConfirmationTimer, m_PublishVerificationTimer,
  155. m_PublishDelayTimer, m_CleanupTimer;
  156. std::string m_Nickname;
  157. int m_LeaseSetType;
  158. std::unique_ptr<i2p::data::Tag<32> > m_LeaseSetPrivKey; // non-null if presented
  159. public:
  160. // for HTTP only
  161. int GetNumRemoteLeaseSets () const { return m_RemoteLeaseSets.size (); };
  162. const decltype(m_RemoteLeaseSets)& GetLeaseSets () const { return m_RemoteLeaseSets; };
  163. bool IsEncryptedLeaseSet () const { return m_LeaseSetType == i2p::data::NETDB_STORE_TYPE_ENCRYPTED_LEASESET2; };
  164. };
  165. class ClientDestination: public LeaseSetDestination
  166. {
  167. public:
  168. #ifdef I2LUA
  169. // type for informing that a client destination is ready
  170. typedef std::promise<std::shared_ptr<ClientDestination> > ReadyPromise;
  171. // informs promise with shared_from_this() when this destination is ready to use
  172. // if cancelled before ready, informs promise with nullptr
  173. void Ready(ReadyPromise & p);
  174. #endif
  175. ClientDestination (const i2p::data::PrivateKeys& keys, bool isPublic, const std::map<std::string, std::string> * params = nullptr);
  176. ~ClientDestination ();
  177. virtual bool Start ();
  178. virtual bool Stop ();
  179. const i2p::data::PrivateKeys& GetPrivateKeys () const { return m_Keys; };
  180. void Sign (const uint8_t * buf, int len, uint8_t * signature) const { m_Keys.Sign (buf, len, signature); };
  181. // ref counter
  182. int Acquire () { return ++m_RefCounter; };
  183. int Release () { return --m_RefCounter; };
  184. int GetRefCounter () const { return m_RefCounter; };
  185. // streaming
  186. std::shared_ptr<i2p::stream::StreamingDestination> CreateStreamingDestination (int port, bool gzip = true); // additional
  187. std::shared_ptr<i2p::stream::StreamingDestination> GetStreamingDestination (int port = 0) const;
  188. // following methods operate with default streaming destination
  189. void CreateStream (StreamRequestComplete streamRequestComplete, const i2p::data::IdentHash& dest, int port = 0);
  190. void CreateStream (StreamRequestComplete streamRequestComplete, std::shared_ptr<const i2p::data::BlindedPublicKey> dest, int port = 0);
  191. std::shared_ptr<i2p::stream::Stream> CreateStream (std::shared_ptr<const i2p::data::LeaseSet> remote, int port = 0);
  192. void AcceptStreams (const i2p::stream::StreamingDestination::Acceptor& acceptor);
  193. void StopAcceptingStreams ();
  194. bool IsAcceptingStreams () const;
  195. void AcceptOnce (const i2p::stream::StreamingDestination::Acceptor& acceptor);
  196. int GetStreamingAckDelay () const { return m_StreamingAckDelay; }
  197. // datagram
  198. i2p::datagram::DatagramDestination * GetDatagramDestination () const { return m_DatagramDestination; };
  199. i2p::datagram::DatagramDestination * CreateDatagramDestination ();
  200. // implements LocalDestination
  201. bool Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx) const;
  202. std::shared_ptr<const i2p::data::IdentityEx> GetIdentity () const { return m_Keys.GetPublic (); };
  203. protected:
  204. void CleanupDestination ();
  205. // I2CP
  206. void HandleDataMessage (const uint8_t * buf, size_t len);
  207. void CreateNewLeaseSet (std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> > tunnels);
  208. private:
  209. std::shared_ptr<ClientDestination> GetSharedFromThis ()
  210. { return std::static_pointer_cast<ClientDestination>(shared_from_this ()); }
  211. void PersistTemporaryKeys ();
  212. #ifdef I2LUA
  213. void ScheduleCheckForReady(ReadyPromise * p);
  214. void HandleCheckForReady(const boost::system::error_code & ecode, ReadyPromise * p);
  215. #endif
  216. void ReadAuthKey (const std::string& group, const std::map<std::string, std::string> * params);
  217. private:
  218. i2p::data::PrivateKeys m_Keys;
  219. uint8_t m_EncryptionPublicKey[256], m_EncryptionPrivateKey[256];
  220. i2p::data::CryptoKeyType m_EncryptionKeyType;
  221. std::shared_ptr<i2p::crypto::CryptoKeyDecryptor> m_Decryptor;
  222. int m_StreamingAckDelay;
  223. std::shared_ptr<i2p::stream::StreamingDestination> m_StreamingDestination; // default
  224. std::map<uint16_t, std::shared_ptr<i2p::stream::StreamingDestination> > m_StreamingDestinationsByPorts;
  225. i2p::datagram::DatagramDestination * m_DatagramDestination;
  226. int m_RefCounter; // how many clients(tunnels) use this destination
  227. boost::asio::deadline_timer m_ReadyChecker;
  228. int m_AuthType;
  229. std::shared_ptr<std::vector<i2p::data::AuthPublicKey> > m_AuthKeys;
  230. public:
  231. // for HTTP only
  232. std::vector<std::shared_ptr<const i2p::stream::Stream> > GetAllStreams () const;
  233. };
  234. }
  235. }
  236. #endif