Multicaster.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 64
  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. }
  70. /**
  71. * Generate a signature of a multicast packet using an identity
  72. *
  73. * @param id Identity to sign with (must have secret key portion)
  74. * @param from MAC address of sender
  75. * @param to Multicast group
  76. * @param etherType 16-bit ethernet type
  77. * @param data Ethernet frame data
  78. * @param len Length of frame
  79. * @return ECDSA signature
  80. */
  81. static inline std::string signMulticastPacket(const Identity &id,const MAC &from,const MulticastGroup &to,unsigned int etherType,const void *data,unsigned int len)
  82. {
  83. unsigned char digest[32];
  84. _hashMulticastPacketForSig(from,to,etherType,data,len,digest);
  85. return id.sign(digest);
  86. }
  87. /**
  88. * Verify a signature from a multicast packet
  89. *
  90. * @param id Identity of original signer
  91. * @param from MAC address of sender
  92. * @param to Multicast group
  93. * @param etherType 16-bit ethernet type
  94. * @param data Ethernet frame data
  95. * @param len Length of frame
  96. * @param signature ECDSA signature
  97. * @param siglen Length of signature in bytes
  98. * @return ECDSA signature
  99. */
  100. static bool verifyMulticastPacket(const Identity &id,const MAC &from,const MulticastGroup &to,unsigned int etherType,const void *data,unsigned int len,const void *signature,unsigned int siglen)
  101. {
  102. unsigned char digest[32];
  103. _hashMulticastPacketForSig(from,to,etherType,data,len,digest);
  104. return id.verify(digest,signature,siglen);
  105. }
  106. /**
  107. * Update the most recent LIKE time for an address in a given multicast group on a given network
  108. *
  109. * @param nwid Network ID
  110. * @param mg Multicast group
  111. * @param addr Address that likes group on given network
  112. * @param now Current timestamp
  113. */
  114. inline void likesMulticastGroup(const uint64_t nwid,const MulticastGroup &mg,const Address &addr,const uint64_t now)
  115. {
  116. _multicastMemberships[MulticastChannel(nwid,mg)][addr] = now;
  117. }
  118. /**
  119. * Check multicast history to see if this is a duplicate, and add/update entry
  120. *
  121. * @param from Ultimate sending MAC address
  122. * @param to Destination multicast group
  123. * @param payload Multicast packet payload
  124. * @param len Length of packet
  125. * @param nwid Network ID
  126. * @param now Current time
  127. * @return True if this appears to be a duplicate to within history expiration time
  128. */
  129. inline bool checkAndUpdateMulticastHistory(
  130. const MAC &from,
  131. const MulticastGroup &to,
  132. const void *payload,
  133. unsigned int len,
  134. const uint64_t nwid,
  135. const uint64_t now)
  136. throw()
  137. {
  138. // Note: CRCs aren't transmitted over the network, so portability and
  139. // byte order don't matter. This calculation can be changed. We just
  140. // want a unique code.
  141. uint64_t crc = Utils::crc64(0,from.data,6);
  142. crc = Utils::crc64(crc,to.mac().data,6);
  143. crc ^= (uint64_t)to.adi();
  144. crc = Utils::crc64(crc,payload,len);
  145. crc ^= nwid; // also include network ID in CRC
  146. // Replace existing entry or pick one to replace with new entry
  147. uint64_t earliest = 0xffffffffffffffffULL;
  148. unsigned long earliestIdx = 0;
  149. for(unsigned int i=0;i<ZT_MULTICAST_DEDUP_HISTORY_LENGTH;++i) {
  150. if (_multicastHistory[i][0] == crc) {
  151. uint64_t then = _multicastHistory[i][1];
  152. _multicastHistory[i][1] = now;
  153. return ((now - then) < ZT_MULTICAST_DEDUP_HISTORY_EXPIRE);
  154. } else if (_multicastHistory[i][1] < earliest) {
  155. earliest = _multicastHistory[i][1];
  156. earliestIdx = i;
  157. }
  158. }
  159. _multicastHistory[earliestIdx][0] = crc; // replace oldest entry
  160. _multicastHistory[earliestIdx][1] = now;
  161. return false;
  162. }
  163. /**
  164. * Choose peers to send a propagating multicast to
  165. *
  166. * @param topology Topology object or mock thereof
  167. * @param nwid Network ID
  168. * @param mg Multicast group
  169. * @param upstream Address from which message originated, or null (0) address if none
  170. * @param bf Bloom filter, updated in place with sums of addresses in chosen peers and/or decay
  171. * @param max Maximum number of peers to pick
  172. * @param peers Array of objects of type P to fill with up to [max] peers
  173. * @param now Current timestamp
  174. * @return Number of peers actually stored in peers array
  175. * @tparam T Type of topology, which is Topology in running code or a mock in simulation
  176. * @tparam P Type of peers, which is SharedPtr<Peer> in running code or a mock in simulation (mock must behave like a pointer type)
  177. */
  178. template<typename T,typename P>
  179. inline unsigned int pickNextPropagationPeers(
  180. T &topology,
  181. uint64_t nwid,
  182. const MulticastGroup &mg,
  183. const Address &upstream,
  184. MulticastBloomFilter &bf,
  185. unsigned int max,
  186. P *peers,
  187. uint64_t now)
  188. {
  189. P toConsider[ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE];
  190. unsigned int sampleSize = 0;
  191. {
  192. Mutex::Lock _l(_multicastMemberships_m);
  193. // Sample a random subset of peers that we know have LIKEd this multicast
  194. // group on this network.
  195. std::map< MulticastChannel,std::map<Address,uint64_t> >::iterator channelMembers(_multicastMemberships.find(MulticastChannel(nwid,mg)));
  196. if ((channelMembers != _multicastMemberships.end())&&(!channelMembers->second.empty())) {
  197. 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;
  198. double skipWhatFraction = (double)numEntriesPermittedToSkip / (double)channelMembers->second.size();
  199. std::map<Address,uint64_t>::iterator channelMemberEntry(channelMembers->second.begin());
  200. while (channelMemberEntry != channelMembers->second.end()) {
  201. // Auto-clean the channel members map if their LIKEs are expired. This will
  202. // technically skew the random distribution of chosen members just a little, but
  203. // it's unlikely that enough will expire in any single pick to make much of a
  204. // difference overall.
  205. if ((now - channelMemberEntry->second) > ZT_MULTICAST_LIKE_EXPIRE) {
  206. channelMembers->second.erase(channelMemberEntry++);
  207. continue;
  208. }
  209. // Skip some fraction of entries so that our sampling will be randomly distributed,
  210. // since there is no other good way to sample randomly from a map.
  211. if (numEntriesPermittedToSkip) {
  212. double skipThis = (double)(Utils::randomInt<uint32_t>()) / 4294967296.0;
  213. if (skipThis <= skipWhatFraction) {
  214. --numEntriesPermittedToSkip;
  215. ++channelMemberEntry;
  216. continue;
  217. }
  218. }
  219. // If it's not expired and it's from our random sample, add it to the set of peers
  220. // to consider.
  221. P peer = topology.getPeer(channelMemberEntry->first);
  222. if (peer) {
  223. toConsider[sampleSize++] = peer;
  224. if (sampleSize >= ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE)
  225. break; // abort if we have enough candidates
  226. }
  227. ++channelMemberEntry;
  228. }
  229. // Auto-clean: erase whole map if there are no more LIKEs for this channel
  230. if (channelMembers->second.empty())
  231. _multicastMemberships.erase(channelMembers);
  232. }
  233. }
  234. // Sort in descending order of most recent direct unicast frame, picking
  235. // peers with whom we have recently communicated. This is "implicit social
  236. // switching."
  237. std::sort(&(toConsider[0]),&(toConsider[sampleSize]),PeerPropagationPrioritySortOrder<P>());
  238. // Decay a few random bits in bloom filter to probabilistically eliminate
  239. // false positives as we go. The odds of decaying an already-set bit
  240. // increases as the bloom filter saturates, so in the early hops of
  241. // propagation this likely won't have any effect.
  242. for(unsigned int i=0;i<ZT_MULTICAST_BLOOM_FILTER_DECAY_RATE;++i)
  243. bf.decay();
  244. // Pick peers not in the bloom filter, setting bloom filter bits accordingly to
  245. // remember and pass on these picks.
  246. unsigned int picked = 0;
  247. for(unsigned int i=0;((i<sampleSize)&&(picked < max));++i) {
  248. if (!bf.set(toConsider[i]->address().sum()))
  249. peers[picked++] = toConsider[i];
  250. }
  251. // Add a supernode if there's nowhere else to go. Supernodes know of all multicast
  252. // LIKEs and so can act to bridge sparse multicast groups. We do not remember them
  253. // in the bloom filter, since such bridging may very well need to happen more than
  254. // once.
  255. if (!picked) {
  256. P peer = topology.getBestSupernode();
  257. if (peer)
  258. peers[picked++] = peer;
  259. }
  260. return picked;
  261. }
  262. private:
  263. // Sort order for chosen propagation peers
  264. template<typename P>
  265. struct PeerPropagationPrioritySortOrder
  266. {
  267. inline bool operator()(const P &p1,const P &p2) const
  268. {
  269. return (p1->lastUnicastFrame() >= p2->lastUnicastFrame());
  270. }
  271. };
  272. static inline void _hashMulticastPacketForSig(const MAC &from,const MulticastGroup &to,unsigned int etherType,const void *data,unsigned int len,unsigned char *digest)
  273. throw()
  274. {
  275. unsigned char zero = 0;
  276. SHA256_CTX sha;
  277. SHA256_Init(&sha);
  278. uint64_t _nwid = Utils::hton(network->id());
  279. SHA256_Update(&sha,(unsigned char *)&_nwid,sizeof(_nwid));
  280. SHA256_Update(&sha,&zero,1);
  281. SHA256_Update(&sha,(unsigned char *)from.data,6);
  282. SHA256_Update(&sha,&zero,1);
  283. SHA256_Update(&sha,(unsigned char *)mg.mac().data,6);
  284. SHA256_Update(&sha,&zero,1);
  285. uint32_t _adi = Utils::hton(mg.adi());
  286. SHA256_Update(&sha,(unsigned char *)&_adi,sizeof(_adi));
  287. SHA256_Update(&sha,&zero,1);
  288. uint16_t _etype = Utils::hton((uint16_t)etherType);
  289. SHA256_Update(&sha,(unsigned char *)&_etype,sizeof(_etype));
  290. SHA256_Update(&sha,&zero,1);
  291. SHA256_Update(&sha,(unsigned char *)data,len);
  292. SHA256_Final(digest,&sha);
  293. }
  294. // [0] - CRC, [1] - timestamp
  295. uint64_t _multicastHistory[ZT_MULTICAST_DEDUP_HISTORY_LENGTH][2];
  296. // A multicast channel, essentially a pub/sub channel. It consists of a
  297. // network ID and a multicast group within that network.
  298. typedef std::pair<uint64_t,MulticastGroup> MulticastChannel;
  299. // Address and time of last LIKE, by network ID and multicast group
  300. std::map< MulticastChannel,std::map<Address,uint64_t> > _multicastMemberships;
  301. Mutex _multicastMemberships_m;
  302. };
  303. } // namespace ZeroTier
  304. #endif