Cluster.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifndef ZT_CLUSTER_HPP
  19. #define ZT_CLUSTER_HPP
  20. #ifdef ZT_ENABLE_CLUSTER
  21. #include <map>
  22. #include "Constants.hpp"
  23. #include "../include/ZeroTierOne.h"
  24. #include "Address.hpp"
  25. #include "InetAddress.hpp"
  26. #include "SHA512.hpp"
  27. #include "Utils.hpp"
  28. #include "Buffer.hpp"
  29. #include "Mutex.hpp"
  30. #include "SharedPtr.hpp"
  31. #include "Hashtable.hpp"
  32. #include "Packet.hpp"
  33. #include "SharedPtr.hpp"
  34. /**
  35. * Timeout for cluster members being considered "alive"
  36. *
  37. * A cluster member is considered dead and will no longer have peers
  38. * redirected to it if we have not heard a heartbeat in this long.
  39. */
  40. #define ZT_CLUSTER_TIMEOUT 5000
  41. /**
  42. * Desired period between doPeriodicTasks() in milliseconds
  43. */
  44. #define ZT_CLUSTER_PERIODIC_TASK_PERIOD 20
  45. /**
  46. * How often to flush outgoing message queues (maximum interval)
  47. */
  48. #define ZT_CLUSTER_FLUSH_PERIOD ZT_CLUSTER_PERIODIC_TASK_PERIOD
  49. /**
  50. * Maximum number of queued outgoing packets per sender address
  51. */
  52. #define ZT_CLUSTER_MAX_QUEUE_PER_SENDER 16
  53. /**
  54. * Expiration time for send queue entries
  55. */
  56. #define ZT_CLUSTER_QUEUE_EXPIRATION 3000
  57. /**
  58. * Chunk size for allocating queue entries
  59. *
  60. * Queue entries are allocated in chunks of this many and are added to a pool.
  61. * ZT_CLUSTER_MAX_QUEUE_GLOBAL must be evenly divisible by this.
  62. */
  63. #define ZT_CLUSTER_QUEUE_CHUNK_SIZE 32
  64. /**
  65. * Maximum number of chunks to ever allocate
  66. *
  67. * This is a global sanity limit to prevent resource exhaustion attacks. It
  68. * works out to about 600mb of RAM. You'll never see this on a normal edge
  69. * node. We're unlikely to see this on a root server unless someone is DOSing
  70. * us. In that case cluster relaying will be affected but other functions
  71. * should continue to operate normally.
  72. */
  73. #define ZT_CLUSTER_MAX_QUEUE_CHUNKS 8194
  74. /**
  75. * Max data per queue entry
  76. */
  77. #define ZT_CLUSTER_SEND_QUEUE_DATA_MAX 1500
  78. namespace ZeroTier {
  79. class RuntimeEnvironment;
  80. class MulticastGroup;
  81. class Peer;
  82. class Identity;
  83. // Internal class implemented inside Cluster.cpp
  84. class _ClusterSendQueue;
  85. /**
  86. * Multi-homing cluster state replication and packet relaying
  87. *
  88. * Multi-homing means more than one node sharing the same ZeroTier identity.
  89. * There is nothing in the protocol to prevent this, but to make it work well
  90. * requires the devices sharing an identity to cooperate and share some
  91. * information.
  92. *
  93. * There are three use cases we want to fulfill:
  94. *
  95. * (1) Multi-homing of root servers with handoff for efficient routing,
  96. * HA, and load balancing across many commodity nodes.
  97. * (2) Multi-homing of network controllers for the same reason.
  98. * (3) Multi-homing of nodes on virtual networks, such as domain servers
  99. * and other important endpoints.
  100. *
  101. * These use cases are in order of escalating difficulty. The initial
  102. * version of Cluster is aimed at satisfying the first, though you are
  103. * free to try #2 and #3.
  104. */
  105. class Cluster
  106. {
  107. public:
  108. /**
  109. * State message types
  110. */
  111. enum StateMessageType
  112. {
  113. CLUSTER_MESSAGE_NOP = 0,
  114. /**
  115. * This cluster member is alive:
  116. * <[2] version minor>
  117. * <[2] version major>
  118. * <[2] version revision>
  119. * <[1] protocol version>
  120. * <[4] X location (signed 32-bit)>
  121. * <[4] Y location (signed 32-bit)>
  122. * <[4] Z location (signed 32-bit)>
  123. * <[8] local clock at this member>
  124. * <[8] load average>
  125. * <[8] number of peers>
  126. * <[8] flags (currently unused, must be zero)>
  127. * <[1] number of preferred ZeroTier endpoints>
  128. * <[...] InetAddress(es) of preferred ZeroTier endpoint(s)>
  129. *
  130. * Cluster members constantly broadcast an alive heartbeat and will only
  131. * receive peer redirects if they've done so within the timeout.
  132. */
  133. CLUSTER_MESSAGE_ALIVE = 1,
  134. /**
  135. * Cluster member has this peer:
  136. * <[...] serialized identity of peer>
  137. *
  138. * This is typically sent in response to WANT_PEER but can also be pushed
  139. * to prepopulate if this makes sense.
  140. */
  141. CLUSTER_MESSAGE_HAVE_PEER = 2,
  142. /**
  143. * Cluster member wants this peer:
  144. * <[5] ZeroTier address of peer>
  145. *
  146. * Members that have a direct link to this peer will respond with
  147. * HAVE_PEER.
  148. */
  149. CLUSTER_MESSAGE_WANT_PEER = 3,
  150. /**
  151. * A remote packet that we should also possibly respond to:
  152. * <[2] 16-bit length of remote packet>
  153. * <[...] remote packet payload>
  154. *
  155. * Cluster members may relay requests by relaying the request packet.
  156. * These may include requests such as WHOIS and MULTICAST_GATHER. The
  157. * packet must be already decrypted, decompressed, and authenticated.
  158. *
  159. * This can only be used for small request packets as per the cluster
  160. * message size limit, but since these are the only ones in question
  161. * this is fine.
  162. *
  163. * If a response is generated it is sent via PROXY_SEND.
  164. */
  165. CLUSTER_MESSAGE_REMOTE_PACKET = 4,
  166. /**
  167. * Request that VERB_RENDEZVOUS be sent to a peer that we have:
  168. * <[5] ZeroTier address of peer on recipient's side>
  169. * <[5] ZeroTier address of peer on sender's side>
  170. * <[1] 8-bit number of sender's peer's active path addresses>
  171. * <[...] series of serialized InetAddresses of sender's peer's paths>
  172. *
  173. * This requests that we perform NAT-t introduction between a peer that
  174. * we have and one on the sender's side. The sender furnishes contact
  175. * info for its peer, and we send VERB_RENDEZVOUS to both sides: to ours
  176. * directly and with PROXY_SEND to theirs.
  177. */
  178. CLUSTER_MESSAGE_PROXY_UNITE = 5,
  179. /**
  180. * Request that a cluster member send a packet to a locally-known peer:
  181. * <[5] ZeroTier address of recipient>
  182. * <[1] packet verb>
  183. * <[2] length of packet payload>
  184. * <[...] packet payload>
  185. *
  186. * This differs from RELAY in that it requests the receiving cluster
  187. * member to actually compose a ZeroTier Packet from itself to the
  188. * provided recipient. RELAY simply says "please forward this blob."
  189. * RELAY is used to implement peer-to-peer relaying with RENDEZVOUS,
  190. * while PROXY_SEND is used to implement proxy sending (which right
  191. * now is only used to send RENDEZVOUS).
  192. */
  193. CLUSTER_MESSAGE_PROXY_SEND = 6,
  194. /**
  195. * Replicate a network config for a network we belong to:
  196. * <[...] network config chunk>
  197. *
  198. * This is used by clusters to avoid every member having to query
  199. * for the same netconf for networks all members belong to.
  200. *
  201. * The first field of a network config chunk is the network ID,
  202. * so this can be checked to look up the network on receipt.
  203. */
  204. CLUSTER_MESSAGE_NETWORK_CONFIG = 7
  205. };
  206. /**
  207. * Construct a new cluster
  208. */
  209. Cluster(
  210. const RuntimeEnvironment *renv,
  211. uint16_t id,
  212. const std::vector<InetAddress> &zeroTierPhysicalEndpoints,
  213. int32_t x,
  214. int32_t y,
  215. int32_t z,
  216. void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
  217. void *sendFunctionArg,
  218. int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
  219. void *addressToLocationFunctionArg);
  220. ~Cluster();
  221. /**
  222. * @return This cluster member's ID
  223. */
  224. inline uint16_t id() const throw() { return _id; }
  225. /**
  226. * Handle an incoming intra-cluster message
  227. *
  228. * @param data Message data
  229. * @param len Message length (max: ZT_CLUSTER_MAX_MESSAGE_LENGTH)
  230. */
  231. void handleIncomingStateMessage(const void *msg,unsigned int len);
  232. /**
  233. * Broadcast that we have a given peer
  234. *
  235. * This should be done when new peers are first contacted.
  236. *
  237. * @param id Identity of peer
  238. */
  239. void broadcastHavePeer(const Identity &id);
  240. /**
  241. * Broadcast a network config chunk to other members of cluster
  242. *
  243. * @param chunk Chunk data
  244. * @param len Length of chunk
  245. */
  246. void broadcastNetworkConfigChunk(const void *chunk,unsigned int len);
  247. /**
  248. * Send this packet via another node in this cluster if another node has this peer
  249. *
  250. * This is used in the outgoing packet and relaying logic in Switch to
  251. * relay packets to other cluster members. It isn't PROXY_SEND-- that is
  252. * used internally in Cluster to send responses to peer queries.
  253. *
  254. * @param fromPeerAddress Source peer address (if known, should be NULL for fragments)
  255. * @param toPeerAddress Destination peer address
  256. * @param data Packet or packet fragment data
  257. * @param len Length of packet or fragment
  258. * @param unite If true, also request proxy unite across cluster
  259. */
  260. void sendViaCluster(const Address &fromPeerAddress,const Address &toPeerAddress,const void *data,unsigned int len,bool unite);
  261. /**
  262. * Send a distributed query to other cluster members
  263. *
  264. * Some queries such as WHOIS or MULTICAST_GATHER need a response from other
  265. * cluster members. Replies (if any) will be sent back to the peer via
  266. * PROXY_SEND across the cluster.
  267. *
  268. * @param pkt Packet to distribute
  269. */
  270. void sendDistributedQuery(const Packet &pkt);
  271. /**
  272. * Call every ~ZT_CLUSTER_PERIODIC_TASK_PERIOD milliseconds.
  273. */
  274. void doPeriodicTasks();
  275. /**
  276. * Add a member ID to this cluster
  277. *
  278. * @param memberId Member ID
  279. */
  280. void addMember(uint16_t memberId);
  281. /**
  282. * Remove a member ID from this cluster
  283. *
  284. * @param memberId Member ID to remove
  285. */
  286. void removeMember(uint16_t memberId);
  287. /**
  288. * Find a better cluster endpoint for this peer (if any)
  289. *
  290. * @param redirectTo InetAddress to be set to a better endpoint (if there is one)
  291. * @param peerAddress Address of peer to (possibly) redirect
  292. * @param peerPhysicalAddress Physical address of peer's current best path (where packet was most recently received or getBestPath()->address())
  293. * @param offload Always redirect if possible -- can be used to offload peers during shutdown
  294. * @return True if redirectTo was set to a new address, false if redirectTo was not modified
  295. */
  296. bool findBetterEndpoint(InetAddress &redirectTo,const Address &peerAddress,const InetAddress &peerPhysicalAddress,bool offload);
  297. /**
  298. * Fill out ZT_ClusterStatus structure (from core API)
  299. *
  300. * @param status Reference to structure to hold result (anything there is replaced)
  301. */
  302. void status(ZT_ClusterStatus &status) const;
  303. private:
  304. void _send(uint16_t memberId,StateMessageType type,const void *msg,unsigned int len);
  305. void _flush(uint16_t memberId);
  306. void _doREMOTE_WHOIS(uint64_t fromMemberId,const Packet &remotep);
  307. void _doREMOTE_MULTICAST_GATHER(uint64_t fromMemberId,const Packet &remotep);
  308. // These are initialized in the constructor and remain immutable ------------
  309. uint16_t _masterSecret[ZT_SHA512_DIGEST_LEN / sizeof(uint16_t)];
  310. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  311. const RuntimeEnvironment *RR;
  312. _ClusterSendQueue *const _sendQueue;
  313. void (*_sendFunction)(void *,unsigned int,const void *,unsigned int);
  314. void *_sendFunctionArg;
  315. int (*_addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *);
  316. void *_addressToLocationFunctionArg;
  317. const int32_t _x;
  318. const int32_t _y;
  319. const int32_t _z;
  320. const uint16_t _id;
  321. const std::vector<InetAddress> _zeroTierPhysicalEndpoints;
  322. // end immutable fields -----------------------------------------------------
  323. struct _Member
  324. {
  325. unsigned char key[ZT_PEER_SECRET_KEY_LENGTH];
  326. uint64_t lastReceivedAliveAnnouncement;
  327. uint64_t lastAnnouncedAliveTo;
  328. uint64_t load;
  329. uint64_t peers;
  330. int32_t x,y,z;
  331. std::vector<InetAddress> zeroTierPhysicalEndpoints;
  332. Buffer<ZT_CLUSTER_MAX_MESSAGE_LENGTH> q;
  333. Mutex lock;
  334. inline void clear()
  335. {
  336. lastReceivedAliveAnnouncement = 0;
  337. lastAnnouncedAliveTo = 0;
  338. load = 0;
  339. peers = 0;
  340. x = 0;
  341. y = 0;
  342. z = 0;
  343. zeroTierPhysicalEndpoints.clear();
  344. q.clear();
  345. }
  346. _Member() { this->clear(); }
  347. ~_Member() { Utils::burn(key,sizeof(key)); }
  348. };
  349. _Member *const _members;
  350. std::vector<uint16_t> _memberIds;
  351. Mutex _memberIds_m;
  352. std::map< std::pair<Address,unsigned int>,uint64_t > _remotePeers; // we need ordered behavior and lower_bound here
  353. Mutex _remotePeers_m;
  354. uint64_t _lastFlushed;
  355. uint64_t _lastCleanedRemotePeers;
  356. uint64_t _lastCleanedQueue;
  357. };
  358. } // namespace ZeroTier
  359. #endif // ZT_ENABLE_CLUSTER
  360. #endif