Multicaster.hpp 13 KB

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