Cluster.hpp 14 KB

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