Multicaster.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. * Compute the CRC64 code for multicast deduplication
  112. *
  113. * @param nwid Network ID
  114. * @param from Sender MAC
  115. * @param to Destination multicast group
  116. * @param etherType Ethernet frame type
  117. * @param payload Multicast frame data
  118. * @param len Length of frame
  119. */
  120. static inline uint64_t computeMulticastDedupCrc(
  121. uint64_t nwid,
  122. const MAC &from,
  123. const MulticastGroup &to,
  124. unsigned int etherType,
  125. const void *payload,
  126. unsigned int len)
  127. throw()
  128. {
  129. // This CRC is only used locally, so byte order issues and
  130. // such don't matter. It can also be changed without protocol
  131. // impact.
  132. uint64_t crc = Utils::crc64(0,from.data,6);
  133. crc = Utils::crc64(crc,to.mac().data,6);
  134. crc ^= (uint64_t)to.adi();
  135. crc ^= (uint64_t)etherType;
  136. crc = Utils::crc64(crc,payload,len);
  137. crc ^= nwid; // also include network ID in CRC
  138. return crc;
  139. }
  140. /**
  141. * Check multicast history to see if this is a duplicate
  142. *
  143. * @param crc Multicast CRC
  144. * @param now Current time
  145. * @return True if this appears to be a duplicate to within history expiration time
  146. */
  147. inline bool checkDuplicate(uint64_t crc,uint64_t now) const
  148. throw()
  149. {
  150. for(unsigned int i=0;i<ZT_MULTICAST_DEDUP_HISTORY_LENGTH;++i) {
  151. if ((_multicastHistory[i][0] == crc)&&((now - _multicastHistory[i][1]) < ZT_MULTICAST_DEDUP_HISTORY_EXPIRE))
  152. return true;
  153. }
  154. return false;
  155. }
  156. /**
  157. * Add a multicast CRC to the multicast deduplication history
  158. *
  159. * @param crc Multicast CRC
  160. * @param now Current time
  161. */
  162. inline void addToDedupHistory(uint64_t crc,uint64_t now)
  163. throw()
  164. {
  165. unsigned int mhi = ++_multicastHistoryPtr % ZT_MULTICAST_DEDUP_HISTORY_LENGTH;
  166. _multicastHistory[mhi][0] = crc;
  167. _multicastHistory[mhi][1] = now;
  168. }
  169. /**
  170. * Update the most recent LIKE time for an address in a given multicast group on a given network
  171. *
  172. * @param nwid Network ID
  173. * @param mg Multicast group
  174. * @param addr Address that likes group on given network
  175. * @param now Current timestamp
  176. */
  177. inline void likesMulticastGroup(const uint64_t nwid,const MulticastGroup &mg,const Address &addr,const uint64_t now)
  178. {
  179. Mutex::Lock _l(_multicastMemberships_m);
  180. std::vector<MulticastMembership> &memberships = _multicastMemberships[MulticastChannel(nwid,mg)];
  181. for(std::vector<MulticastMembership>::iterator mm(memberships.begin());mm!=memberships.end();++mm) {
  182. if (mm->first == addr) {
  183. mm->second = now;
  184. return;
  185. }
  186. }
  187. memberships.push_back(MulticastMembership(addr,now));
  188. }
  189. /**
  190. * Choose peers to send a propagating multicast to
  191. *
  192. * @param topology Topology object or mock thereof
  193. * @param nwid Network ID
  194. * @param mg Multicast group
  195. * @param originalSubmitter Original submitter of multicast message to network
  196. * @param upstream Address from which message originated, or null (0) address if none
  197. * @param bf Bloom filter, updated in place with sums of addresses in chosen peers and/or decay
  198. * @param max Maximum number of peers to pick
  199. * @param peers Array of objects of type P to fill with up to [max] peers
  200. * @param now Current timestamp
  201. * @return Number of peers actually stored in peers array
  202. * @tparam T Type of topology, which is Topology in running code or a mock in simulation
  203. * @tparam P Type of peers, which is SharedPtr<Peer> in running code or a mock in simulation (mock must behave like a pointer type)
  204. */
  205. template<typename T,typename P>
  206. inline unsigned int pickNextPropagationPeers(
  207. CMWC4096 &prng,
  208. T &topology,
  209. uint64_t nwid,
  210. const MulticastGroup &mg,
  211. const Address &originalSubmitter,
  212. const Address &upstream,
  213. MulticastBloomFilter &bf,
  214. unsigned int max,
  215. P *peers,
  216. uint64_t now)
  217. {
  218. typename std::set< P,_PeerPropagationPrioritySortOrder<P> > toConsider;
  219. // Pick up to ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE peers that have
  220. // subscribed to this channel and that are not in bloom filter.
  221. // Pick randomly from subscribers, but place into a set that is
  222. // sorted in descending order of time of most recent unicast
  223. // frame transfer. (Implicit social ordering.) Also ignore original
  224. // submitter and upstream, since we know these have seen this
  225. // message.
  226. {
  227. Mutex::Lock _l(_multicastMemberships_m);
  228. std::map< MulticastChannel,std::vector<MulticastMembership> >::iterator mm(_multicastMemberships.find(MulticastChannel(nwid,mg)));
  229. if ((mm != _multicastMemberships.end())&&(!mm->second.empty())) {
  230. for(unsigned int stries=0;stries<ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE;++stries) {
  231. MulticastMembership &m = mm->second[prng.next32() % mm->second.size()];
  232. if (((now - m.second) < ZT_MULTICAST_LIKE_EXPIRE)&&(!bf.contains(m.first.sum()))&&(m.first != originalSubmitter)&&(m.first != upstream)) {
  233. P peer(topology.getPeer(m.first));
  234. if (peer)
  235. toConsider.insert(peer);
  236. }
  237. }
  238. }
  239. }
  240. // The first peers in toConsider will be the 'best'
  241. unsigned int chosen = 0;
  242. for(typename std::set< P,_PeerPropagationPrioritySortOrder<P> >::iterator i(toConsider.begin());((i!=toConsider.end())&&(chosen < max));++i)
  243. bf.set((peers[chosen++] = *i)->address().sum());
  244. // Add a supernode if there are fewer than the desired
  245. // number of recipients.
  246. if (chosen < max) {
  247. P peer = topology.getBestSupernode(&originalSubmitter,1,true);
  248. if (peer)
  249. peers[chosen++] = peer;
  250. }
  251. return chosen;
  252. }
  253. private:
  254. // Sort order for chosen propagation peers
  255. template<typename P>
  256. struct _PeerPropagationPrioritySortOrder
  257. {
  258. inline bool operator()(const P &p1,const P &p2) const
  259. {
  260. return (p1->lastUnicastFrame() > p2->lastUnicastFrame());
  261. }
  262. };
  263. 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)
  264. throw()
  265. {
  266. unsigned char zero = 0;
  267. SHA256_CTX sha;
  268. SHA256_Init(&sha);
  269. uint64_t _nwid = Utils::hton(nwid);
  270. SHA256_Update(&sha,(unsigned char *)&_nwid,sizeof(_nwid));
  271. SHA256_Update(&sha,&zero,1);
  272. SHA256_Update(&sha,(unsigned char *)from.data,6);
  273. SHA256_Update(&sha,&zero,1);
  274. SHA256_Update(&sha,(unsigned char *)to.mac().data,6);
  275. SHA256_Update(&sha,&zero,1);
  276. uint32_t _adi = Utils::hton(to.adi());
  277. SHA256_Update(&sha,(unsigned char *)&_adi,sizeof(_adi));
  278. SHA256_Update(&sha,&zero,1);
  279. uint16_t _etype = Utils::hton((uint16_t)etherType);
  280. SHA256_Update(&sha,(unsigned char *)&_etype,sizeof(_etype));
  281. SHA256_Update(&sha,&zero,1);
  282. SHA256_Update(&sha,(unsigned char *)data,len);
  283. SHA256_Final(digest,&sha);
  284. }
  285. // ring buffer: [0] - CRC, [1] - timestamp
  286. uint64_t _multicastHistory[ZT_MULTICAST_DEDUP_HISTORY_LENGTH][2];
  287. volatile unsigned int _multicastHistoryPtr;
  288. // A multicast channel, essentially a pub/sub channel. It consists of a
  289. // network ID and a multicast group within that network.
  290. typedef std::pair<uint64_t,MulticastGroup> MulticastChannel;
  291. // Address and time of last LIKE
  292. typedef std::pair<Address,uint64_t> MulticastMembership;
  293. std::map< MulticastChannel,std::vector<MulticastMembership> > _multicastMemberships;
  294. Mutex _multicastMemberships_m;
  295. };
  296. } // namespace ZeroTier
  297. #endif