Multicaster.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef _ZT_MULTICASTER_HPP
  28. #define _ZT_MULTICASTER_HPP
  29. #include <stdint.h>
  30. #include <string.h>
  31. #include <openssl/sha.h>
  32. #include <utility>
  33. #include <algorithm>
  34. #include <map>
  35. #include <set>
  36. #include <vector>
  37. #include <string>
  38. #include "Constants.hpp"
  39. #include "Buffer.hpp"
  40. #include "Packet.hpp"
  41. #include "MulticastGroup.hpp"
  42. #include "Utils.hpp"
  43. #include "MAC.hpp"
  44. #include "Address.hpp"
  45. #include "SharedPtr.hpp"
  46. #include "BloomFilter.hpp"
  47. #include "Identity.hpp"
  48. // Maximum sample size to pick during choice of multicast propagation peers
  49. #define ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE 32
  50. namespace ZeroTier {
  51. /**
  52. * Multicast propagation engine
  53. *
  54. * This is written as a generic class so that it can be mocked and tested
  55. * in simulation. It also always takes 'now' as an argument, permitting
  56. * running in simulated time.
  57. */
  58. class Multicaster
  59. {
  60. public:
  61. /**
  62. * 256-bit simple bloom filter included with multicast frame packets
  63. */
  64. typedef BloomFilter<ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BITS> MulticastBloomFilter;
  65. Multicaster()
  66. throw()
  67. {
  68. memset(_multicastHistory,0,sizeof(_multicastHistory));
  69. _multicastHistoryPtr = 0;
  70. }
  71. /**
  72. * Generate a signature of a multicast packet using an identity
  73. *
  74. * @param id Identity to sign with (must have secret key portion)
  75. * @param nwid Network ID
  76. * @param from MAC address of sender
  77. * @param to Multicast group
  78. * @param etherType 16-bit ethernet type
  79. * @param data Ethernet frame data
  80. * @param len Length of frame
  81. * @return ECDSA signature
  82. */
  83. static inline std::string signMulticastPacket(const Identity &id,uint64_t nwid,const MAC &from,const MulticastGroup &to,unsigned int etherType,const void *data,unsigned int len)
  84. {
  85. unsigned char digest[32];
  86. _hashMulticastPacketForSig(nwid,from,to,etherType,data,len,digest);
  87. return id.sign(digest);
  88. }
  89. /**
  90. * Verify a signature from a multicast packet
  91. *
  92. * @param id Identity of original signer
  93. * @param nwid Network ID
  94. * @param from MAC address of sender
  95. * @param to Multicast group
  96. * @param etherType 16-bit ethernet type
  97. * @param data Ethernet frame data
  98. * @param len Length of frame
  99. * @param signature ECDSA signature
  100. * @param siglen Length of signature in bytes
  101. * @return ECDSA signature
  102. */
  103. static bool verifyMulticastPacket(const Identity &id,uint64_t nwid,const MAC &from,const MulticastGroup &to,unsigned int etherType,const void *data,unsigned int len,const void *signature,unsigned int siglen)
  104. {
  105. unsigned char digest[32];
  106. _hashMulticastPacketForSig(nwid,from,to,etherType,data,len,digest);
  107. return id.verifySignature(digest,signature,siglen);
  108. }
  109. /**
  110. * Update the most recent LIKE time for an address in a given multicast group on a given network
  111. *
  112. * @param nwid Network ID
  113. * @param mg Multicast group
  114. * @param addr Address that likes group on given network
  115. * @param now Current timestamp
  116. */
  117. inline void likesMulticastGroup(const uint64_t nwid,const MulticastGroup &mg,const Address &addr,const uint64_t now)
  118. {
  119. _multicastMemberships[MulticastChannel(nwid,mg)][addr] = now;
  120. }
  121. /**
  122. * Compute the CRC64 code for multicast deduplication
  123. *
  124. * @param nwid Network ID
  125. * @param from Sender MAC
  126. * @param to Destination multicast group
  127. * @param etherType Ethernet frame type
  128. * @param payload Multicast frame data
  129. * @param len Length of frame
  130. */
  131. static inline uint64_t computeMulticastDedupCrc(
  132. uint64_t nwid,
  133. const MAC &from,
  134. const MulticastGroup &to,
  135. unsigned int etherType,
  136. const void *payload,
  137. unsigned int len)
  138. throw()
  139. {
  140. // This CRC is only used locally, so byte order issues and
  141. // such don't matter. It can also be changed without protocol
  142. // impact.
  143. uint64_t crc = Utils::crc64(0,from.data,6);
  144. crc = Utils::crc64(crc,to.mac().data,6);
  145. crc ^= (uint64_t)to.adi();
  146. crc ^= (uint64_t)etherType;
  147. crc = Utils::crc64(crc,payload,len);
  148. crc ^= nwid; // also include network ID in CRC
  149. return crc;
  150. }
  151. /**
  152. * Check multicast history to see if this is a duplicate
  153. *
  154. * @param crc Multicast CRC
  155. * @param now Current time
  156. * @return True if this appears to be a duplicate to within history expiration time
  157. */
  158. inline bool checkDuplicate(uint64_t crc,uint64_t now) const
  159. throw()
  160. {
  161. for(unsigned int i=0;i<ZT_MULTICAST_DEDUP_HISTORY_LENGTH;++i) {
  162. if ((_multicastHistory[i][0] == crc)&&((now - _multicastHistory[i][1]) < ZT_MULTICAST_DEDUP_HISTORY_EXPIRE))
  163. return true;
  164. }
  165. return false;
  166. }
  167. /**
  168. * Add a multicast CRC to the multicast deduplication history
  169. *
  170. * @param crc Multicast CRC
  171. * @param now Current time
  172. */
  173. inline void addToDedupHistory(uint64_t crc,uint64_t now)
  174. throw()
  175. {
  176. unsigned int mhi = ++_multicastHistoryPtr % ZT_MULTICAST_DEDUP_HISTORY_LENGTH;
  177. _multicastHistory[mhi][0] = crc;
  178. _multicastHistory[mhi][1] = now;
  179. }
  180. /**
  181. * Choose peers to send a propagating multicast to
  182. *
  183. * @param topology Topology object or mock thereof
  184. * @param nwid Network ID
  185. * @param mg Multicast group
  186. * @param originalSubmitter Original submitter of multicast message to network
  187. * @param upstream Address from which message originated, or null (0) address if none
  188. * @param bf Bloom filter, updated in place with sums of addresses in chosen peers and/or decay
  189. * @param max Maximum number of peers to pick
  190. * @param peers Array of objects of type P to fill with up to [max] peers
  191. * @param now Current timestamp
  192. * @return Number of peers actually stored in peers array
  193. * @tparam T Type of topology, which is Topology in running code or a mock in simulation
  194. * @tparam P Type of peers, which is SharedPtr<Peer> in running code or a mock in simulation (mock must behave like a pointer type)
  195. */
  196. template<typename T,typename P>
  197. inline unsigned int pickNextPropagationPeers(
  198. T &topology,
  199. uint64_t nwid,
  200. const MulticastGroup &mg,
  201. const Address &originalSubmitter,
  202. const Address &upstream,
  203. MulticastBloomFilter &bf,
  204. unsigned int max,
  205. P *peers,
  206. uint64_t now)
  207. {
  208. P toConsider[ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE];
  209. unsigned int sampleSize = 0;
  210. {
  211. Mutex::Lock _l(_multicastMemberships_m);
  212. // Sample a random subset of peers that we know have LIKEd this multicast
  213. // group on this network.
  214. std::map< MulticastChannel,std::map<Address,uint64_t> >::iterator channelMembers(_multicastMemberships.find(MulticastChannel(nwid,mg)));
  215. if ((channelMembers != _multicastMemberships.end())&&(!channelMembers->second.empty())) {
  216. unsigned long numEntriesPermittedToSkip = (channelMembers->second.size() > ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE) ? (unsigned long)(channelMembers->second.size() - ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE) : (unsigned long)0;
  217. double skipWhatFraction = (double)numEntriesPermittedToSkip / (double)channelMembers->second.size();
  218. std::map<Address,uint64_t>::iterator channelMemberEntry(channelMembers->second.begin());
  219. while (channelMemberEntry != channelMembers->second.end()) {
  220. // Auto-clean the channel members map if their LIKEs are expired. This will
  221. // technically skew the random distribution of chosen members just a little, but
  222. // it's unlikely that enough will expire in any single pick to make much of a
  223. // difference overall.
  224. if ((now - channelMemberEntry->second) > ZT_MULTICAST_LIKE_EXPIRE) {
  225. channelMembers->second.erase(channelMemberEntry++);
  226. continue;
  227. }
  228. // Skip some fraction of entries so that our sampling will be randomly distributed,
  229. // since there is no other good way to sample randomly from a map.
  230. if (numEntriesPermittedToSkip) {
  231. double skipThis = (double)(Utils::randomInt<uint32_t>()) / 4294967296.0;
  232. if (skipThis <= skipWhatFraction) {
  233. --numEntriesPermittedToSkip;
  234. ++channelMemberEntry;
  235. continue;
  236. }
  237. }
  238. // If it's not expired and it's from our random sample, add it to the set of peers
  239. // to consider. Exclude immediate upstream and original submitter, since we know for
  240. // a fact they've already seen this.
  241. if ((channelMemberEntry->first != originalSubmitter)&&(channelMemberEntry->first != upstream)) {
  242. P peer = topology.getPeer(channelMemberEntry->first);
  243. if ((peer)&&(peer->hasActiveDirectPath(now))) {
  244. toConsider[sampleSize++] = peer;
  245. if (sampleSize >= ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE)
  246. break; // abort if we have enough candidates
  247. }
  248. }
  249. ++channelMemberEntry;
  250. }
  251. // Auto-clean: erase whole map if there are no more LIKEs for this channel
  252. if (channelMembers->second.empty())
  253. _multicastMemberships.erase(channelMembers);
  254. }
  255. }
  256. // Sort in descending order of most recent direct unicast frame, picking
  257. // peers with whom we have recently communicated. This is "implicit social
  258. // switching."
  259. std::sort(toConsider,toConsider + sampleSize,PeerPropagationPrioritySortOrder<P>());
  260. // Decay a few random bits in bloom filter to probabilistically eliminate
  261. // false positives as we go. The odds of decaying an already-set bit
  262. // increases as the bloom filter saturates, so in the early hops of
  263. // propagation this likely won't have any effect. This allows peers with
  264. // bloom filter collisions to be reconsidered, but at positions on the
  265. // network graph likely to be hops away from the original origin of the
  266. // message.
  267. for(unsigned int i=0;i<ZT_MULTICAST_BLOOM_FILTER_DECAY_RATE;++i)
  268. bf.decay();
  269. // Pick peers not in the bloom filter, setting bloom filter bits accordingly to
  270. // remember and pass on these picks.
  271. unsigned int picked = 0;
  272. for(unsigned int i=0;((i<sampleSize)&&(picked < max));++i) {
  273. if (!bf.set(toConsider[i]->address().sum()))
  274. peers[picked++] = toConsider[i];
  275. }
  276. // Add a supernode if there's nowhere else to go. Supernodes know of all multicast
  277. // LIKEs and so can act to bridge sparse multicast groups.
  278. if (!picked) {
  279. P peer = topology.getBestSupernode(&originalSubmitter,1,true);
  280. if (peer)
  281. peers[picked++] = peer;
  282. }
  283. return picked;
  284. }
  285. private:
  286. // Sort order for chosen propagation peers
  287. template<typename P>
  288. struct PeerPropagationPrioritySortOrder
  289. {
  290. inline bool operator()(const P &p1,const P &p2) const
  291. {
  292. return (p1->lastUnicastFrame() > p2->lastUnicastFrame());
  293. }
  294. };
  295. static inline void _hashMulticastPacketForSig(uint64_t nwid,const MAC &from,const MulticastGroup &to,unsigned int etherType,const void *data,unsigned int len,unsigned char *digest)
  296. throw()
  297. {
  298. unsigned char zero = 0;
  299. SHA256_CTX sha;
  300. SHA256_Init(&sha);
  301. uint64_t _nwid = Utils::hton(nwid);
  302. SHA256_Update(&sha,(unsigned char *)&_nwid,sizeof(_nwid));
  303. SHA256_Update(&sha,&zero,1);
  304. SHA256_Update(&sha,(unsigned char *)from.data,6);
  305. SHA256_Update(&sha,&zero,1);
  306. SHA256_Update(&sha,(unsigned char *)to.mac().data,6);
  307. SHA256_Update(&sha,&zero,1);
  308. uint32_t _adi = Utils::hton(to.adi());
  309. SHA256_Update(&sha,(unsigned char *)&_adi,sizeof(_adi));
  310. SHA256_Update(&sha,&zero,1);
  311. uint16_t _etype = Utils::hton((uint16_t)etherType);
  312. SHA256_Update(&sha,(unsigned char *)&_etype,sizeof(_etype));
  313. SHA256_Update(&sha,&zero,1);
  314. SHA256_Update(&sha,(unsigned char *)data,len);
  315. SHA256_Final(digest,&sha);
  316. }
  317. // ring buffer: [0] - CRC, [1] - timestamp
  318. uint64_t _multicastHistory[ZT_MULTICAST_DEDUP_HISTORY_LENGTH][2];
  319. volatile unsigned int _multicastHistoryPtr;
  320. // A multicast channel, essentially a pub/sub channel. It consists of a
  321. // network ID and a multicast group within that network.
  322. typedef std::pair<uint64_t,MulticastGroup> MulticastChannel;
  323. // Address and time of last LIKE, by network ID and multicast group
  324. std::map< MulticastChannel,std::map<Address,uint64_t> > _multicastMemberships;
  325. Mutex _multicastMemberships_m;
  326. };
  327. } // namespace ZeroTier
  328. #endif