Multicaster.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 for multicast propagation via random selection
  194. *
  195. * @param prng Random source
  196. * @param topology Topology object or mock thereof
  197. * @param nwid Network ID
  198. * @param mg Multicast group
  199. * @param originalSubmitter Original submitter of multicast message to network
  200. * @param upstream Address from which message originated, or null (0) address if none
  201. * @param bf Bloom filter, updated in place with sums of addresses in chosen peers and/or decay
  202. * @param max Maximum number of peers to pick
  203. * @param peers Array of objects of type P to fill with up to [max] peers
  204. * @param now Current timestamp
  205. * @return Number of peers actually stored in peers array
  206. * @tparam T Type of topology, which is Topology in running code or a mock in simulation
  207. * @tparam P Type of peers, which is SharedPtr<Peer> in running code or a mock in simulation (mock must behave like a pointer type)
  208. */
  209. template<typename T,typename P>
  210. inline unsigned int pickRandomPropagationPeers(
  211. CMWC4096 &prng,
  212. T &topology,
  213. uint64_t nwid,
  214. const MulticastGroup &mg,
  215. const Address &originalSubmitter,
  216. const Address &upstream,
  217. MulticastBloomFilter &bf,
  218. unsigned int max,
  219. P *peers,
  220. uint64_t now)
  221. {
  222. unsigned int chosen = 0;
  223. Mutex::Lock _l(_multicastMemberships_m);
  224. std::map< MulticastChannel,std::vector<MulticastMembership> >::iterator mm(_multicastMemberships.find(MulticastChannel(nwid,mg)));
  225. if ((mm != _multicastMemberships.end())&&(!mm->second.empty())) {
  226. for(unsigned int stries=0;((stries<ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE)&&(chosen < max));++stries) {
  227. MulticastMembership &m = mm->second[prng.next32() % mm->second.size()];
  228. unsigned int sum = m.first.sum();
  229. if (
  230. ((now - m.second) < ZT_MULTICAST_LIKE_EXPIRE)&& /* LIKE is not expired */
  231. (!bf.contains(sum))&& /* Not in propagation bloom */
  232. (m.first != originalSubmitter)&& /* Not the original submitter */
  233. (m.first != upstream) ) { /* Not where the frame came from */
  234. P peer(topology.getPeer(m.first));
  235. if (peer) {
  236. unsigned int chk = 0;
  237. while (chk < chosen) {
  238. if (peers[chk] == peer)
  239. break;
  240. ++chk;
  241. }
  242. if (chk == chosen) { /* not already picked */
  243. peers[chosen++] = peer;
  244. bf.set(sum);
  245. }
  246. }
  247. }
  248. }
  249. }
  250. return chosen;
  251. }
  252. /**
  253. * Choose peers for multicast propagation via implicit social switching
  254. *
  255. * @param prng Random source
  256. * @param topology Topology object or mock thereof
  257. * @param nwid Network ID
  258. * @param mg Multicast group
  259. * @param originalSubmitter Original submitter of multicast message to network
  260. * @param upstream Address from which message originated, or null (0) address if none
  261. * @param bf Bloom filter, updated in place with sums of addresses in chosen peers and/or decay
  262. * @param max Maximum number of peers to pick
  263. * @param peers Array of objects of type P to fill with up to [max] peers
  264. * @param now Current timestamp
  265. * @return Number of peers actually stored in peers array
  266. * @tparam T Type of topology, which is Topology in running code or a mock in simulation
  267. * @tparam P Type of peers, which is SharedPtr<Peer> in running code or a mock in simulation (mock must behave like a pointer type)
  268. */
  269. template<typename T,typename P>
  270. inline unsigned int pickSocialPropagationPeers(
  271. CMWC4096 &prng,
  272. T &topology,
  273. uint64_t nwid,
  274. const MulticastGroup &mg,
  275. const Address &originalSubmitter,
  276. const Address &upstream,
  277. MulticastBloomFilter &bf,
  278. unsigned int max,
  279. P *peers,
  280. uint64_t now)
  281. {
  282. typename std::set< P,_PeerPropagationPrioritySortOrder<P> > toConsider;
  283. /* Pick up to ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE peers that meet
  284. * our minimal criteria for this multicast group and place them
  285. * into a set that is sorted in descending order of time of most
  286. * recent unicast frame transfer (implicit social ordering). */
  287. {
  288. Mutex::Lock _l(_multicastMemberships_m);
  289. std::map< MulticastChannel,std::vector<MulticastMembership> >::iterator mm(_multicastMemberships.find(MulticastChannel(nwid,mg)));
  290. if ((mm != _multicastMemberships.end())&&(!mm->second.empty())) {
  291. for(unsigned int stries=0;stries<ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE;++stries) {
  292. MulticastMembership &m = mm->second[prng.next32() % mm->second.size()];
  293. if (
  294. ((now - m.second) < ZT_MULTICAST_LIKE_EXPIRE)&& /* LIKE is not expired */
  295. (!bf.contains(m.first.sum()))&& /* Not in propagation bloom */
  296. (m.first != originalSubmitter)&& /* Not the original submitter */
  297. (m.first != upstream) ) { /* Not where the frame came from */
  298. P peer(topology.getPeer(m.first));
  299. if (peer)
  300. toConsider.insert(peer); /* Consider propagating to this peer */
  301. }
  302. }
  303. }
  304. }
  305. /* The first peers in toConsider will be the "best" */
  306. unsigned int chosen = 0;
  307. for(typename std::set< P,_PeerPropagationPrioritySortOrder<P> >::iterator i(toConsider.begin());((i!=toConsider.end())&&(chosen < max));++i)
  308. bf.set((peers[chosen++] = *i)->address().sum());
  309. /* Tack on a supernode if we have no next hops */
  310. if (!chosen) {
  311. Address exclude[1];
  312. exclude[0] = originalSubmitter; // if it came from a supernode, don't boomerang
  313. P peer = topology.getBestSupernode(exclude,1,true);
  314. if (peer)
  315. peers[chosen++] = peer;
  316. }
  317. return chosen;
  318. }
  319. private:
  320. // Sort order for chosen propagation peers
  321. template<typename P>
  322. struct _PeerPropagationPrioritySortOrder
  323. {
  324. inline bool operator()(const P &p1,const P &p2) const
  325. {
  326. return (p1->lastUnicastFrame() > p2->lastUnicastFrame());
  327. }
  328. };
  329. 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)
  330. throw()
  331. {
  332. unsigned char zero = 0;
  333. SHA256_CTX sha;
  334. SHA256_Init(&sha);
  335. uint64_t _nwid = Utils::hton(nwid);
  336. SHA256_Update(&sha,(unsigned char *)&_nwid,sizeof(_nwid));
  337. SHA256_Update(&sha,&zero,1);
  338. SHA256_Update(&sha,(unsigned char *)from.data,6);
  339. SHA256_Update(&sha,&zero,1);
  340. SHA256_Update(&sha,(unsigned char *)to.mac().data,6);
  341. SHA256_Update(&sha,&zero,1);
  342. uint32_t _adi = Utils::hton(to.adi());
  343. SHA256_Update(&sha,(unsigned char *)&_adi,sizeof(_adi));
  344. SHA256_Update(&sha,&zero,1);
  345. uint16_t _etype = Utils::hton((uint16_t)etherType);
  346. SHA256_Update(&sha,(unsigned char *)&_etype,sizeof(_etype));
  347. SHA256_Update(&sha,&zero,1);
  348. SHA256_Update(&sha,(unsigned char *)data,len);
  349. SHA256_Final(digest,&sha);
  350. }
  351. // ring buffer: [0] - CRC, [1] - timestamp
  352. uint64_t _multicastHistory[ZT_MULTICAST_DEDUP_HISTORY_LENGTH][2];
  353. volatile unsigned int _multicastHistoryPtr;
  354. // A multicast channel, essentially a pub/sub channel. It consists of a
  355. // network ID and a multicast group within that network.
  356. typedef std::pair<uint64_t,MulticastGroup> MulticastChannel;
  357. // A membership in a multicast channel, an address and time of last LIKE
  358. typedef std::pair<Address,uint64_t> MulticastMembership;
  359. // Network : MulticastGroup -> vector<Address : time of last LIKE>
  360. std::map< MulticastChannel,std::vector<MulticastMembership> > _multicastMemberships;
  361. Mutex _multicastMemberships_m;
  362. };
  363. } // namespace ZeroTier
  364. #endif