Multicaster.hpp 13 KB

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