Multicaster.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 <utility>
  32. #include <algorithm>
  33. #include <stdexcept>
  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. #include "C25519.hpp"
  50. // Maximum sample size to pick during choice of multicast propagation peers
  51. #define ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE (ZT_MULTICAST_PROPAGATION_BREADTH * 8)
  52. namespace ZeroTier {
  53. /**
  54. * Multicast propagation engine
  55. *
  56. * This is written as a generic class so that it can be mocked and tested
  57. * in simulation. It also always takes 'now' as an argument, permitting
  58. * running in simulated time.
  59. *
  60. * This does not handle network permission or rate limiting, only the
  61. * propagation algorithm.
  62. */
  63. class Multicaster
  64. {
  65. public:
  66. /**
  67. * Simple bit field bloom filter included with multicast frame packets
  68. */
  69. typedef BloomFilter<ZT_PROTO_VERB_MULTICAST_FRAME_BLOOM_FILTER_SIZE_BITS> MulticastBloomFilter;
  70. Multicaster()
  71. throw()
  72. {
  73. memset(_multicastHistory,0,sizeof(_multicastHistory));
  74. _multicastHistoryPtr = 0;
  75. }
  76. /**
  77. * Generate a signature of a multicast packet using an identity
  78. *
  79. * @param id Identity to sign with (must have secret key portion)
  80. * @param nwid Network ID
  81. * @param from MAC address of sender
  82. * @param to Multicast group
  83. * @param etherType 16-bit ethernet type
  84. * @param data Ethernet frame data
  85. * @param len Length of frame
  86. * @return Signature of packet data and attributes
  87. * @throws std::runtime_error Cannot sign, e.g. identity has no private key
  88. */
  89. static inline C25519::Signature signMulticastPacket(const Identity &id,uint64_t nwid,const MAC &from,const MulticastGroup &to,unsigned int etherType,const void *data,unsigned int len)
  90. throw(std::runtime_error)
  91. {
  92. char tmp[65536];
  93. void *tmp2 = (void *)tmp;
  94. *((uint64_t *)tmp2) = Utils::hton((uint64_t)nwid);
  95. memcpy(tmp + 8,from.data,6);
  96. memcpy(tmp + 14,to.mac().data,6);
  97. *((uint32_t *)(tmp + 20)) = Utils::hton((uint32_t)to.adi());
  98. *((uint16_t *)(tmp + 24)) = Utils::hton((uint16_t)etherType);
  99. memcpy(tmp + 26,data,std::min((unsigned int)(sizeof(tmp) - 26),len)); // min() is a sanity check here, no packet is that big
  100. return id.sign(tmp,len + 26);
  101. }
  102. /**
  103. * Verify a signature from a multicast packet
  104. *
  105. * @param id Identity of original signer
  106. * @param nwid Network ID
  107. * @param from MAC address of sender
  108. * @param to Multicast group
  109. * @param etherType 16-bit ethernet type
  110. * @param data Ethernet frame data
  111. * @param len Length of frame
  112. * @param signature Signature
  113. * @param siglen Length of signature in bytes
  114. * @return True if signature verification was successful
  115. */
  116. 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)
  117. {
  118. char tmp[65536];
  119. void *tmp2 = (void *)tmp;
  120. *((uint64_t *)tmp2) = Utils::hton(nwid);
  121. memcpy(tmp + 8,from.data,6);
  122. memcpy(tmp + 14,to.mac().data,6);
  123. *((uint32_t *)(tmp + 20)) = Utils::hton(to.adi());
  124. *((uint16_t *)(tmp + 24)) = Utils::hton((uint16_t)etherType);
  125. memcpy(tmp + 26,data,std::min((unsigned int)(sizeof(tmp) - 26),len)); // min() is a sanity check here, no packet is that big
  126. return id.verify(tmp,len + 26,signature,siglen);
  127. }
  128. /**
  129. * Compute the CRC64 code for multicast deduplication
  130. *
  131. * @param nwid Network ID
  132. * @param from Sender MAC
  133. * @param to Destination multicast group
  134. * @param etherType Ethernet frame type
  135. * @param payload Multicast frame data
  136. * @param len Length of frame
  137. */
  138. static inline uint64_t computeMulticastDedupCrc(
  139. uint64_t nwid,
  140. const MAC &from,
  141. const MulticastGroup &to,
  142. unsigned int etherType,
  143. const void *payload,
  144. unsigned int len)
  145. throw()
  146. {
  147. // This CRC is only used locally, so byte order issues and
  148. // such don't matter. It can also be changed without protocol
  149. // impact.
  150. uint64_t crc = Utils::crc64(0,from.data,6);
  151. crc = Utils::crc64(crc,to.mac().data,6);
  152. crc ^= (uint64_t)to.adi();
  153. crc ^= (uint64_t)etherType;
  154. crc = Utils::crc64(crc,payload,len);
  155. crc ^= nwid; // also include network ID in CRC
  156. return crc;
  157. }
  158. /**
  159. * Check multicast history to see if this is a duplicate
  160. *
  161. * @param crc Multicast CRC
  162. * @param now Current time
  163. * @return True if this appears to be a duplicate to within history expiration time
  164. */
  165. inline bool checkDuplicate(uint64_t crc,uint64_t now) const
  166. throw()
  167. {
  168. for(unsigned int i=0;i<ZT_MULTICAST_DEDUP_HISTORY_LENGTH;++i) {
  169. if ((_multicastHistory[i][0] == crc)&&((now - _multicastHistory[i][1]) < ZT_MULTICAST_DEDUP_HISTORY_EXPIRE))
  170. return true;
  171. }
  172. return false;
  173. }
  174. /**
  175. * Add a multicast CRC to the multicast deduplication history
  176. *
  177. * @param crc Multicast CRC
  178. * @param now Current time
  179. */
  180. inline void addToDedupHistory(uint64_t crc,uint64_t now)
  181. throw()
  182. {
  183. unsigned int mhi = ++_multicastHistoryPtr % ZT_MULTICAST_DEDUP_HISTORY_LENGTH;
  184. _multicastHistory[mhi][0] = crc;
  185. _multicastHistory[mhi][1] = now;
  186. }
  187. /**
  188. * Update the most recent LIKE time for an address in a given multicast group on a given network
  189. *
  190. * @param nwid Network ID
  191. * @param mg Multicast group
  192. * @param addr Address that likes group on given network
  193. * @param now Current timestamp
  194. */
  195. inline void likesMulticastGroup(const uint64_t nwid,const MulticastGroup &mg,const Address &addr,const uint64_t now)
  196. {
  197. Mutex::Lock _l(_multicastMemberships_m);
  198. std::vector<MulticastMembership> &memberships = _multicastMemberships[MulticastChannel(nwid,mg)];
  199. for(std::vector<MulticastMembership>::iterator mm(memberships.begin());mm!=memberships.end();++mm) {
  200. if (mm->first == addr) {
  201. mm->second = now;
  202. return;
  203. }
  204. }
  205. memberships.push_back(MulticastMembership(addr,now));
  206. }
  207. /**
  208. * Choose peers for multicast propagation via random selection
  209. *
  210. * @param prng Random source
  211. * @param topology Topology object or mock thereof
  212. * @param nwid Network ID
  213. * @param mg Multicast group
  214. * @param originalSubmitter Original submitter of multicast message to network
  215. * @param upstream Address from which message originated, or null (0) address if none
  216. * @param bf Bloom filter, updated in place with sums of addresses in chosen peers and/or decay
  217. * @param max Maximum number of peers to pick
  218. * @param peers Array of objects of type P to fill with up to [max] peers
  219. * @param now Current timestamp
  220. * @return Number of peers actually stored in peers array
  221. * @tparam T Type of topology, which is Topology in running code or a mock in simulation
  222. * @tparam P Type of peers, which is SharedPtr<Peer> in running code or a mock in simulation (mock must behave like a pointer type)
  223. */
  224. template<typename T,typename P>
  225. inline unsigned int pickRandomPropagationPeers(
  226. CMWC4096 &prng,
  227. T &topology,
  228. uint64_t nwid,
  229. const MulticastGroup &mg,
  230. const Address &originalSubmitter,
  231. const Address &upstream,
  232. MulticastBloomFilter &bf,
  233. unsigned int max,
  234. P *peers,
  235. uint64_t now)
  236. {
  237. unsigned int chosen = 0;
  238. Mutex::Lock _l(_multicastMemberships_m);
  239. std::map< MulticastChannel,std::vector<MulticastMembership> >::iterator mm(_multicastMemberships.find(MulticastChannel(nwid,mg)));
  240. if ((mm != _multicastMemberships.end())&&(!mm->second.empty())) {
  241. for(unsigned int stries=0;((stries<ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE)&&(chosen < max));++stries) {
  242. MulticastMembership &m = mm->second[prng.next32() % mm->second.size()];
  243. unsigned int sum = m.first.sum();
  244. if (
  245. ((now - m.second) < ZT_MULTICAST_LIKE_EXPIRE)&& /* LIKE is not expired */
  246. (!bf.contains(sum))&& /* Not in propagation bloom */
  247. (m.first != originalSubmitter)&& /* Not the original submitter */
  248. (m.first != upstream) ) { /* Not where the frame came from */
  249. P peer(topology.getPeer(m.first));
  250. if (peer) {
  251. unsigned int chk = 0;
  252. while (chk < chosen) {
  253. if (peers[chk] == peer)
  254. break;
  255. ++chk;
  256. }
  257. if (chk == chosen) { /* not already picked */
  258. peers[chosen++] = peer;
  259. bf.set(sum);
  260. }
  261. }
  262. }
  263. }
  264. }
  265. return chosen;
  266. }
  267. /**
  268. * Choose peers for multicast propagation via implicit social switching
  269. *
  270. * @param prng Random source
  271. * @param topology Topology object or mock thereof
  272. * @param nwid Network ID
  273. * @param mg Multicast group
  274. * @param originalSubmitter Original submitter of multicast message to network
  275. * @param upstream Address from which message originated, or null (0) address if none
  276. * @param bf Bloom filter, updated in place with sums of addresses in chosen peers and/or decay
  277. * @param max Maximum number of peers to pick
  278. * @param peers Array of objects of type P to fill with up to [max] peers
  279. * @param now Current timestamp
  280. * @return Number of peers actually stored in peers array
  281. * @tparam T Type of topology, which is Topology in running code or a mock in simulation
  282. * @tparam P Type of peers, which is SharedPtr<Peer> in running code or a mock in simulation (mock must behave like a pointer type)
  283. */
  284. template<typename T,typename P>
  285. inline unsigned int pickSocialPropagationPeers(
  286. CMWC4096 &prng,
  287. T &topology,
  288. uint64_t nwid,
  289. const MulticastGroup &mg,
  290. const Address &originalSubmitter,
  291. const Address &upstream,
  292. MulticastBloomFilter &bf,
  293. unsigned int max,
  294. P *peers,
  295. uint64_t now)
  296. {
  297. typename std::set< P,_PeerPropagationPrioritySortOrder<P> > toConsider;
  298. /* Pick up to ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE peers that meet
  299. * our minimal criteria for this multicast group and place them
  300. * into a set that is sorted in descending order of time of most
  301. * recent unicast frame transfer (implicit social ordering). */
  302. {
  303. Mutex::Lock _l(_multicastMemberships_m);
  304. std::map< MulticastChannel,std::vector<MulticastMembership> >::iterator mm(_multicastMemberships.find(MulticastChannel(nwid,mg)));
  305. if ((mm != _multicastMemberships.end())&&(!mm->second.empty())) {
  306. for(unsigned int stries=0;stries<ZT_MULTICAST_PICK_MAX_SAMPLE_SIZE;++stries) {
  307. MulticastMembership &m = mm->second[prng.next32() % mm->second.size()];
  308. if (
  309. ((now - m.second) < ZT_MULTICAST_LIKE_EXPIRE)&& /* LIKE is not expired */
  310. (!bf.contains(m.first.sum()))&& /* Not in propagation bloom */
  311. (m.first != originalSubmitter)&& /* Not the original submitter */
  312. (m.first != upstream) ) { /* Not where the frame came from */
  313. P peer(topology.getPeer(m.first));
  314. if (peer)
  315. toConsider.insert(peer); /* Consider propagating to this peer */
  316. }
  317. }
  318. }
  319. }
  320. /* The first peers in toConsider will be the "best" */
  321. unsigned int chosen = 0;
  322. for(typename std::set< P,_PeerPropagationPrioritySortOrder<P> >::iterator i(toConsider.begin());((i!=toConsider.end())&&(chosen < max));++i)
  323. bf.set((peers[chosen++] = *i)->address().sum());
  324. /* Tack on a supernode if we have no next hops */
  325. if (!chosen) {
  326. Address exclude[1];
  327. exclude[0] = originalSubmitter; // if it came from a supernode, don't boomerang
  328. P peer = topology.getBestSupernode(exclude,1,true);
  329. if (peer)
  330. peers[chosen++] = peer;
  331. }
  332. return chosen;
  333. }
  334. private:
  335. // Sort order for chosen propagation peers
  336. template<typename P>
  337. struct _PeerPropagationPrioritySortOrder
  338. {
  339. inline bool operator()(const P &p1,const P &p2) const
  340. {
  341. return (p1->lastUnicastFrame() > p2->lastUnicastFrame());
  342. }
  343. };
  344. // ring buffer: [0] - CRC, [1] - timestamp
  345. uint64_t _multicastHistory[ZT_MULTICAST_DEDUP_HISTORY_LENGTH][2];
  346. volatile unsigned int _multicastHistoryPtr;
  347. // A multicast channel, essentially a pub/sub channel. It consists of a
  348. // network ID and a multicast group within that network.
  349. typedef std::pair<uint64_t,MulticastGroup> MulticastChannel;
  350. // A membership in a multicast channel, an address and time of last LIKE
  351. typedef std::pair<Address,uint64_t> MulticastMembership;
  352. // Network : MulticastGroup -> vector<Address : time of last LIKE>
  353. std::map< MulticastChannel,std::vector<MulticastMembership> > _multicastMemberships;
  354. Mutex _multicastMemberships_m;
  355. };
  356. } // namespace ZeroTier
  357. #endif