Multicaster.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. * This does not handle network permission or rate limiting, only the
  60. * propagation algorithm.
  61. */
  62. class Multicaster
  63. {
  64. public:
  65. /**
  66. * Simple bit field bloom filter included with multicast frame packets
  67. */
  68. typedef BloomFilter<ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BITS> MulticastBloomFilter;
  69. Multicaster()
  70. throw()
  71. {
  72. memset(_multicastHistory,0,sizeof(_multicastHistory));
  73. _multicastHistoryPtr = 0;
  74. }
  75. /**
  76. * Generate a signature of a multicast packet using an identity
  77. *
  78. * @param id Identity to sign with (must have secret key portion)
  79. * @param nwid Network ID
  80. * @param from MAC address of sender
  81. * @param to Multicast group
  82. * @param etherType 16-bit ethernet type
  83. * @param data Ethernet frame data
  84. * @param len Length of frame
  85. * @return ECDSA signature
  86. */
  87. 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)
  88. {
  89. unsigned char digest[32];
  90. _hashMulticastPacketForSig(nwid,from,to,etherType,data,len,digest);
  91. return id.sign(digest);
  92. }
  93. /**
  94. * Verify a signature from a multicast packet
  95. *
  96. * @param id Identity of original signer
  97. * @param nwid Network ID
  98. * @param from MAC address of sender
  99. * @param to Multicast group
  100. * @param etherType 16-bit ethernet type
  101. * @param data Ethernet frame data
  102. * @param len Length of frame
  103. * @param signature ECDSA signature
  104. * @param siglen Length of signature in bytes
  105. * @return ECDSA signature
  106. */
  107. 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)
  108. {
  109. unsigned char digest[32];
  110. _hashMulticastPacketForSig(nwid,from,to,etherType,data,len,digest);
  111. return id.verifySignature(digest,signature,siglen);
  112. }
  113. /**
  114. * Compute the CRC64 code for multicast deduplication
  115. *
  116. * @param nwid Network ID
  117. * @param from Sender MAC
  118. * @param to Destination multicast group
  119. * @param etherType Ethernet frame type
  120. * @param payload Multicast frame data
  121. * @param len Length of frame
  122. */
  123. static inline uint64_t computeMulticastDedupCrc(
  124. uint64_t nwid,
  125. const MAC &from,
  126. const MulticastGroup &to,
  127. unsigned int etherType,
  128. const void *payload,
  129. unsigned int len)
  130. throw()
  131. {
  132. // This CRC is only used locally, so byte order issues and
  133. // such don't matter. It can also be changed without protocol
  134. // impact.
  135. uint64_t crc = Utils::crc64(0,from.data,6);
  136. crc = Utils::crc64(crc,to.mac().data,6);
  137. crc ^= (uint64_t)to.adi();
  138. crc ^= (uint64_t)etherType;
  139. crc = Utils::crc64(crc,payload,len);
  140. crc ^= nwid; // also include network ID in CRC
  141. return crc;
  142. }
  143. /**
  144. * Check multicast history to see if this is a duplicate
  145. *
  146. * @param crc Multicast CRC
  147. * @param now Current time
  148. * @return True if this appears to be a duplicate to within history expiration time
  149. */
  150. inline bool checkDuplicate(uint64_t crc,uint64_t now) const
  151. throw()
  152. {
  153. for(unsigned int i=0;i<ZT_MULTICAST_DEDUP_HISTORY_LENGTH;++i) {
  154. if ((_multicastHistory[i][0] == crc)&&((now - _multicastHistory[i][1]) < ZT_MULTICAST_DEDUP_HISTORY_EXPIRE))
  155. return true;
  156. }
  157. return false;
  158. }
  159. /**
  160. * Add a multicast CRC to the multicast deduplication history
  161. *
  162. * @param crc Multicast CRC
  163. * @param now Current time
  164. */
  165. inline void addToDedupHistory(uint64_t crc,uint64_t now)
  166. throw()
  167. {
  168. unsigned int mhi = ++_multicastHistoryPtr % ZT_MULTICAST_DEDUP_HISTORY_LENGTH;
  169. _multicastHistory[mhi][0] = crc;
  170. _multicastHistory[mhi][1] = now;
  171. }
  172. /**
  173. * Update the most recent LIKE time for an address in a given multicast group on a given network
  174. *
  175. * @param nwid Network ID
  176. * @param mg Multicast group
  177. * @param addr Address that likes group on given network
  178. * @param now Current timestamp
  179. */
  180. inline void likesMulticastGroup(const uint64_t nwid,const MulticastGroup &mg,const Address &addr,const uint64_t now)
  181. {
  182. Mutex::Lock _l(_multicastMemberships_m);
  183. std::vector<MulticastMembership> &memberships = _multicastMemberships[MulticastChannel(nwid,mg)];
  184. for(std::vector<MulticastMembership>::iterator mm(memberships.begin());mm!=memberships.end();++mm) {
  185. if (mm->first == addr) {
  186. mm->second = now;
  187. return;
  188. }
  189. }
  190. memberships.push_back(MulticastMembership(addr,now));
  191. }
  192. /**
  193. * Choose peers to send a propagating multicast to
  194. *
  195. * @param topology Topology object or mock thereof
  196. * @param nwid Network ID
  197. * @param mg Multicast group
  198. * @param originalSubmitter Original submitter of multicast message to network
  199. * @param upstream Address from which message originated, or null (0) address if none
  200. * @param bf Bloom filter, updated in place with sums of addresses in chosen peers and/or decay
  201. * @param max Maximum number of peers to pick
  202. * @param peers Array of objects of type P to fill with up to [max] peers
  203. * @param now Current timestamp
  204. * @return Number of peers actually stored in peers array
  205. * @tparam T Type of topology, which is Topology in running code or a mock in simulation
  206. * @tparam P Type of peers, which is SharedPtr<Peer> in running code or a mock in simulation (mock must behave like a pointer type)
  207. */
  208. template<typename T,typename P>
  209. inline unsigned int pickNextPropagationPeers(
  210. CMWC4096 &prng,
  211. T &topology,
  212. uint64_t nwid,
  213. const MulticastGroup &mg,
  214. const Address &originalSubmitter,
  215. const Address &upstream,
  216. MulticastBloomFilter &bf,
  217. unsigned int max,
  218. P *peers,
  219. uint64_t now)
  220. {
  221. typename std::set< P,_PeerPropagationPrioritySortOrder<P> > toConsider;
  222. // Pick up to ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE peers that have
  223. // subscribed to this channel and that are not in bloom filter.
  224. // Pick randomly from subscribers, but place into a set that is
  225. // sorted in descending order of time of most recent unicast
  226. // frame transfer. (Implicit social ordering.) Also ignore original
  227. // submitter and upstream, since we know these have seen this
  228. // message.
  229. {
  230. Mutex::Lock _l(_multicastMemberships_m);
  231. std::map< MulticastChannel,std::vector<MulticastMembership> >::iterator mm(_multicastMemberships.find(MulticastChannel(nwid,mg)));
  232. if ((mm != _multicastMemberships.end())&&(!mm->second.empty())) {
  233. for(unsigned int stries=0;stries<ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE;++stries) {
  234. MulticastMembership &m = mm->second[prng.next32() % mm->second.size()];
  235. if (((now - m.second) < ZT_MULTICAST_LIKE_EXPIRE)&&(!bf.contains(m.first.sum()))&&(m.first != originalSubmitter)&&(m.first != upstream)) {
  236. P peer(topology.getPeer(m.first));
  237. if (peer)
  238. toConsider.insert(peer);
  239. }
  240. }
  241. }
  242. }
  243. // The first peers in toConsider will be the 'best'
  244. unsigned int chosen = 0;
  245. for(typename std::set< P,_PeerPropagationPrioritySortOrder<P> >::iterator i(toConsider.begin());((i!=toConsider.end())&&(chosen < max));++i)
  246. bf.set((peers[chosen++] = *i)->address().sum());
  247. // Add a supernode if there are fewer than the desired
  248. // number of recipients. Note that we do not use the bloom
  249. // filter to track visits to supernodes, intentionally
  250. // allowing multicasts to ping pong between supernodes.
  251. // Supernodes propagate even messages they've already seen,
  252. // while regular nodes do not. Thus this ping-ponging will
  253. // cause the supernodes to pick new starting points for
  254. // peer to peer graph traversal multiple times. It's a
  255. // simple, stateless way to increase supernode-driven
  256. // propagation of a multicast in the event that peer to
  257. // peer connectivity for its group is sparse.
  258. if (chosen < max) {
  259. Address avoid[2];
  260. avoid[0] = originalSubmitter;
  261. avoid[1] = upstream;
  262. P peer = topology.getBestSupernode(avoid,2,true);
  263. if (peer)
  264. peers[chosen++] = peer;
  265. }
  266. return chosen;
  267. }
  268. private:
  269. // Sort order for chosen propagation peers
  270. template<typename P>
  271. struct _PeerPropagationPrioritySortOrder
  272. {
  273. inline bool operator()(const P &p1,const P &p2) const
  274. {
  275. return (p1->lastUnicastFrame() > p2->lastUnicastFrame());
  276. }
  277. };
  278. 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)
  279. throw()
  280. {
  281. unsigned char zero = 0;
  282. SHA256_CTX sha;
  283. SHA256_Init(&sha);
  284. uint64_t _nwid = Utils::hton(nwid);
  285. SHA256_Update(&sha,(unsigned char *)&_nwid,sizeof(_nwid));
  286. SHA256_Update(&sha,&zero,1);
  287. SHA256_Update(&sha,(unsigned char *)from.data,6);
  288. SHA256_Update(&sha,&zero,1);
  289. SHA256_Update(&sha,(unsigned char *)to.mac().data,6);
  290. SHA256_Update(&sha,&zero,1);
  291. uint32_t _adi = Utils::hton(to.adi());
  292. SHA256_Update(&sha,(unsigned char *)&_adi,sizeof(_adi));
  293. SHA256_Update(&sha,&zero,1);
  294. uint16_t _etype = Utils::hton((uint16_t)etherType);
  295. SHA256_Update(&sha,(unsigned char *)&_etype,sizeof(_etype));
  296. SHA256_Update(&sha,&zero,1);
  297. SHA256_Update(&sha,(unsigned char *)data,len);
  298. SHA256_Final(digest,&sha);
  299. }
  300. // ring buffer: [0] - CRC, [1] - timestamp
  301. uint64_t _multicastHistory[ZT_MULTICAST_DEDUP_HISTORY_LENGTH][2];
  302. volatile unsigned int _multicastHistoryPtr;
  303. // A multicast channel, essentially a pub/sub channel. It consists of a
  304. // network ID and a multicast group within that network.
  305. typedef std::pair<uint64_t,MulticastGroup> MulticastChannel;
  306. // Address and time of last LIKE
  307. typedef std::pair<Address,uint64_t> MulticastMembership;
  308. // Network : MulticastGroup -> vector<Address : time of last LIKE>
  309. std::map< MulticastChannel,std::vector<MulticastMembership> > _multicastMemberships;
  310. Mutex _multicastMemberships_m;
  311. };
  312. } // namespace ZeroTier
  313. #endif