Multicaster.hpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 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 <stdexcept>
  32. #include <map>
  33. #include <set>
  34. #include <list>
  35. #include <algorithm>
  36. #include "Constants.hpp"
  37. #include "Mutex.hpp"
  38. #include "MulticastGroup.hpp"
  39. #include "Topology.hpp"
  40. #include "Address.hpp"
  41. #include "Buffer.hpp"
  42. namespace ZeroTier {
  43. /**
  44. * Multicast propagation algorithm core and database
  45. */
  46. class Multicaster
  47. {
  48. public:
  49. Multicaster();
  50. ~Multicaster();
  51. /**
  52. * Add or renew a peer's subscription to a multicast group
  53. *
  54. * @param nwid Network ID
  55. * @param a Address that LIKEd
  56. * @param mg Multicast group
  57. * @param now Current time
  58. */
  59. void likesGroup(uint64_t nwid,const Address &a,const MulticastGroup &mg,uint64_t now);
  60. /**
  61. * Bring a peer closer in terms of propagation priority
  62. *
  63. * This gets called from PacketDecoder when a unicast frame is received.
  64. *
  65. * @param nwid Network ID
  66. * @param a Address to bring closer (e.g. due to unicast message)
  67. * @param now Current time
  68. */
  69. void bringCloser(uint64_t nwid,const Address &a);
  70. /**
  71. * Erase entries for expired LIKEs and GOT records
  72. */
  73. void clean();
  74. /**
  75. * Multicast deduplicator
  76. *
  77. * This checks to see if a multicast GUID has been seen before. If not, it
  78. * adds it to the history and returns false.
  79. *
  80. * @param nwid Network ID
  81. * @param mcGuid Multicast GUID (sender address + sender unique ID)
  82. * @return True if multicast IS a duplicate, false otherwise
  83. */
  84. inline bool deduplicate(uint64_t nwid,uint64_t mcGuid)
  85. throw()
  86. {
  87. Mutex::Lock _l(_lock);
  88. _NetInfo &n = _nets[nwid];
  89. for(unsigned int i=0;i<ZT_MULTICAST_DEDUP_HISTORY_LENGTH;++i) {
  90. if (n.multicastHistory[i] == mcGuid)
  91. return true;
  92. }
  93. n.multicastHistory[n.multicastHistoryPtr++ % ZT_MULTICAST_DEDUP_HISTORY_LENGTH] = mcGuid;
  94. return false;
  95. }
  96. /**
  97. * Pick next hops for a multicast by proximity
  98. *
  99. * The function or function object must return true if more hops are desired
  100. * or false to stop finding new hops and return.
  101. *
  102. * @param nwid Network ID
  103. * @param mg Multicast group
  104. * @param nextHopFunc Function to call for each address, search stops if it returns false
  105. * @tparam F Function to receive each next hop address
  106. */
  107. template<typename F>
  108. inline void getNextHops(uint64_t nwid,const MulticastGroup &mg,F nextHopFunc)
  109. {
  110. Mutex::Lock _l(_lock);
  111. std::map< uint64_t,_NetInfo >::iterator n(_nets.find(nwid));
  112. if (n == _nets.end())
  113. return;
  114. std::map< MulticastGroup,std::list< Address > >::iterator p(n->second.proximity.find(mg));
  115. if (p == n->second.proximity.end())
  116. return;
  117. for(std::list< Address >::iterator a(p->second.begin());a!=p->second.end();++a) {
  118. if (!nextHopFunc(*a))
  119. break;
  120. }
  121. }
  122. /**
  123. * Functor to add addresses to multicast frame propagation queues
  124. *
  125. * This function object checks the origin, bloom filter, and restriction
  126. * prefix for each address and if all these pass it adds the address and
  127. * increments the pointer pointed to by ptr. It stops (returns false) when
  128. * *ptr reaches end. It's used in PacketDecoder and Switch with getNextHops()
  129. * to compose multicast frame headers.
  130. */
  131. class AddToPropagationQueue
  132. {
  133. public:
  134. /**
  135. * @param ptr Pointer to pointer to current position in queue
  136. * @param end End of queue
  137. * @param bloom Bloom filter field (must be 1024 bytes in length)
  138. * @param bloomNonce Random nonce for bloom filter randomization
  139. * @param origin Originating address
  140. * @param prefixBits Number of bits in propagation restriction prefix
  141. * @param prefix Propagation restrition prefix
  142. * @param topology Topology database
  143. * @param now Current time
  144. */
  145. AddToPropagationQueue(
  146. unsigned char **ptr,
  147. unsigned char *end,
  148. unsigned char *bloom,
  149. uint16_t bloomNonce,
  150. const Address &origin,
  151. unsigned int prefixBits,
  152. uint64_t prefix,
  153. const Topology *topology,
  154. uint64_t now)
  155. throw() :
  156. _origin(origin),
  157. _bloomNonce((uint64_t)bloomNonce),
  158. _prefix(prefix),
  159. _now(now),
  160. _ptr(ptr),
  161. _end(end),
  162. _bloom(bloom),
  163. _topology(topology),
  164. _prefixBits(prefixBits) {}
  165. /**
  166. * @param a Address to (possibly) add
  167. * @return True if FIFO still contains room for more possible addresses
  168. */
  169. inline bool operator()(const Address &a)
  170. throw()
  171. {
  172. if (*_ptr >= _end)
  173. return false;
  174. // Exclude original sender -- obviously they've already seen it
  175. if (a == _origin)
  176. return true;
  177. // Exclude addresses not in this prefix domain
  178. if (!a.withinMulticastPropagationPrefix(_prefix,_prefixBits))
  179. return true;
  180. // Exclude addresses remembered in bloom filter
  181. uint64_t aint = a.toInt() + _bloomNonce;
  182. const unsigned int bit = (unsigned int)(aint ^ (aint >> 13) ^ (aint >> 26) ^ (aint >> 39)) & 0x1fff;
  183. unsigned char *const bbyte = _bloom + (bit >> 3); // note: bloom filter size == 1024 is hard-coded here
  184. const unsigned char bmask = 1 << (bit & 7);
  185. if ((*bbyte & bmask))
  186. return true; // address already visited
  187. // Exclude peers that don't appear to be online
  188. SharedPtr<Peer> p(_topology->getPeer(a));
  189. if ((!p)||(!p->alive(_now)))
  190. return true;
  191. // Remember address in bloom filter
  192. *bbyte |= bmask;
  193. a.copyTo(*_ptr,ZT_ADDRESS_LENGTH);
  194. return ((*_ptr += ZT_ADDRESS_LENGTH) < _end);
  195. }
  196. private:
  197. const Address _origin;
  198. const uint64_t _bloomNonce;
  199. const uint64_t _prefix;
  200. const uint64_t _now;
  201. unsigned char **const _ptr;
  202. unsigned char *const _end;
  203. unsigned char *const _bloom;
  204. const Topology *const _topology;
  205. const unsigned int _prefixBits;
  206. };
  207. private:
  208. // Information about a subscription
  209. struct _SubInfo
  210. {
  211. _SubInfo() :
  212. lastLike(0),
  213. proximitySlot() {}
  214. // Time of last MULTICAST_LIKE for this group
  215. uint64_t lastLike;
  216. // Slot in corresponding list in _proximity
  217. std::list< Address >::iterator proximitySlot;
  218. };
  219. // An address and multicast group tuple
  220. typedef std::pair< Address,MulticastGroup > _Subscription;
  221. // Multicast info for a given network
  222. struct _NetInfo
  223. {
  224. _NetInfo()
  225. throw()
  226. {
  227. memset(multicastHistory,0,sizeof(multicastHistory));
  228. multicastHistoryPtr = 0;
  229. }
  230. // Ring buffer of most recently injected multicast packet GUIDs
  231. uint64_t multicastHistory[ZT_MULTICAST_DEDUP_HISTORY_LENGTH];
  232. unsigned int multicastHistoryPtr;
  233. // Peer proximity ordering for peers subscribed to each group
  234. std::map< MulticastGroup,std::list< Address > > proximity;
  235. // Peer subscriptions to multicast groups
  236. std::map< _Subscription,_SubInfo > subscriptions;
  237. };
  238. std::map< uint64_t,_NetInfo > _nets;
  239. Mutex _lock;
  240. };
  241. } // namespace ZeroTier
  242. #endif