Network.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  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. #ifndef ZT_NETWORK_HPP
  19. #define ZT_NETWORK_HPP
  20. #include <stdint.h>
  21. #include "../include/ZeroTierOne.h"
  22. #include <string>
  23. #include <map>
  24. #include <vector>
  25. #include <algorithm>
  26. #include <stdexcept>
  27. #include "Constants.hpp"
  28. #include "NonCopyable.hpp"
  29. #include "Hashtable.hpp"
  30. #include "Address.hpp"
  31. #include "Mutex.hpp"
  32. #include "SharedPtr.hpp"
  33. #include "AtomicCounter.hpp"
  34. #include "MulticastGroup.hpp"
  35. #include "MAC.hpp"
  36. #include "Dictionary.hpp"
  37. #include "Multicaster.hpp"
  38. #include "Membership.hpp"
  39. #include "NetworkConfig.hpp"
  40. #include "CertificateOfMembership.hpp"
  41. namespace ZeroTier {
  42. class RuntimeEnvironment;
  43. class Peer;
  44. class _MulticastAnnounceAll;
  45. /**
  46. * A virtual LAN
  47. */
  48. class Network : NonCopyable
  49. {
  50. friend class SharedPtr<Network>;
  51. friend class _MulticastAnnounceAll; // internal function object
  52. public:
  53. /**
  54. * Broadcast multicast group: ff:ff:ff:ff:ff:ff / 0
  55. */
  56. static const MulticastGroup BROADCAST;
  57. /**
  58. * Construct a new network
  59. *
  60. * Note that init() should be called immediately after the network is
  61. * constructed to actually configure the port.
  62. *
  63. * @param renv Runtime environment
  64. * @param nwid Network ID
  65. * @param uptr Arbitrary pointer used by externally-facing API (for user use)
  66. */
  67. Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr);
  68. ~Network();
  69. /**
  70. * Apply filters to an outgoing packet
  71. *
  72. * This applies filters from our network config and, if that doesn't match,
  73. * our capabilities in ascending order of capability ID. If there is a match
  74. * certain actions may be taken such as pushing credentials to ztDest and
  75. * sending a copy of the packet to a TEE or REDIRECT target.
  76. *
  77. * @param ztSource Source ZeroTier address
  78. * @param ztDest Destination ZeroTier address
  79. * @param macSource Ethernet layer source address
  80. * @param macDest Ethernet layer destination address
  81. * @param frameData Ethernet frame data
  82. * @param frameLen Ethernet frame payload length
  83. * @param etherType 16-bit ethernet type ID
  84. * @param vlanId 16-bit VLAN ID
  85. * @return True if packet should be sent to destination peer
  86. */
  87. bool filterOutgoingPacket(
  88. const Address &ztSource,
  89. const Address &ztDest,
  90. const MAC &macSource,
  91. const MAC &macDest,
  92. const uint8_t *frameData,
  93. const unsigned int frameLen,
  94. const unsigned int etherType,
  95. const unsigned int vlanId);
  96. /**
  97. * Apply filters to an incoming packet
  98. *
  99. * This applies filters from our network config and, if that doesn't match,
  100. * the peer's capabilities in ascending order of capability ID. If there is
  101. * a match certain actions may be taken such as sending a copy of the packet
  102. * to a TEE or REDIRECT target.
  103. *
  104. * @param sourcePeer Source Peer
  105. * @param ztDest Destination ZeroTier address
  106. * @param macSource Ethernet layer source address
  107. * @param macDest Ethernet layer destination address
  108. * @param frameData Ethernet frame data
  109. * @param frameLen Ethernet frame payload length
  110. * @param etherType 16-bit ethernet type ID
  111. * @param vlanId 16-bit VLAN ID
  112. * @return True if packet should be accepted locally
  113. */
  114. bool filterIncomingPacket(
  115. const SharedPtr<Peer> &sourcePeer,
  116. const Address &ztDest,
  117. const MAC &macSource,
  118. const MAC &macDest,
  119. const uint8_t *frameData,
  120. const unsigned int frameLen,
  121. const unsigned int etherType,
  122. const unsigned int vlanId);
  123. /**
  124. * @return Network ID
  125. */
  126. inline uint64_t id() const throw() { return _id; }
  127. /**
  128. * @return Address of network's controller (most significant 40 bits of ID)
  129. */
  130. inline Address controller() const throw() { return Address(_id >> 24); }
  131. /**
  132. * @param nwid Network ID
  133. * @return Address of network's controller
  134. */
  135. static inline Address controllerFor(uint64_t nwid) throw() { return Address(nwid >> 24); }
  136. /**
  137. * @return Multicast group memberships for this network's port (local, not learned via bridging)
  138. */
  139. inline std::vector<MulticastGroup> multicastGroups() const
  140. {
  141. Mutex::Lock _l(_lock);
  142. return _myMulticastGroups;
  143. }
  144. /**
  145. * @return All multicast groups including learned groups that are behind any bridges we're attached to
  146. */
  147. inline std::vector<MulticastGroup> allMulticastGroups() const
  148. {
  149. Mutex::Lock _l(_lock);
  150. return _allMulticastGroups();
  151. }
  152. /**
  153. * @param mg Multicast group
  154. * @param includeBridgedGroups If true, also include any groups we've learned via bridging
  155. * @return True if this network endpoint / peer is a member
  156. */
  157. bool subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const;
  158. /**
  159. * Subscribe to a multicast group
  160. *
  161. * @param mg New multicast group
  162. */
  163. void multicastSubscribe(const MulticastGroup &mg);
  164. /**
  165. * Unsubscribe from a multicast group
  166. *
  167. * @param mg Multicast group
  168. */
  169. void multicastUnsubscribe(const MulticastGroup &mg);
  170. /**
  171. * Announce multicast groups to a peer if that peer is authorized on this network
  172. *
  173. * @param peer Peer to try to announce multicast groups to
  174. * @return True if peer was authorized and groups were announced
  175. */
  176. bool tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer);
  177. /**
  178. * Apply a NetworkConfig to this network
  179. *
  180. * @param conf Configuration in NetworkConfig form
  181. * @return True if configuration was accepted
  182. */
  183. bool applyConfiguration(const NetworkConfig &conf);
  184. /**
  185. * Set or update this network's configuration
  186. *
  187. * @param nconf Network configuration
  188. * @param saveToDisk IF true (default), write config to disk
  189. * @return 0 -- rejected, 1 -- accepted but not new, 2 -- accepted new config
  190. */
  191. int setConfiguration(const NetworkConfig &nconf,bool saveToDisk);
  192. /**
  193. * Set netconf failure to 'access denied' -- called in IncomingPacket when controller reports this
  194. */
  195. inline void setAccessDenied()
  196. {
  197. Mutex::Lock _l(_lock);
  198. _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
  199. }
  200. /**
  201. * Set netconf failure to 'not found' -- called by PacketDecider when controller reports this
  202. */
  203. inline void setNotFound()
  204. {
  205. Mutex::Lock _l(_lock);
  206. _netconfFailure = NETCONF_FAILURE_NOT_FOUND;
  207. }
  208. /**
  209. * Causes this network to request an updated configuration from its master node now
  210. */
  211. void requestConfiguration();
  212. /**
  213. * @param peer Peer to check
  214. * @return True if peer is allowed to communicate on this network
  215. */
  216. inline bool isAllowed(const SharedPtr<Peer> &peer) const
  217. {
  218. Mutex::Lock _l(_lock);
  219. return _isAllowed(peer);
  220. }
  221. /**
  222. * Perform cleanup and possibly save state
  223. */
  224. void clean();
  225. /**
  226. * @return Time of last updated configuration or 0 if none
  227. */
  228. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  229. /**
  230. * @return Status of this network
  231. */
  232. inline ZT_VirtualNetworkStatus status() const
  233. {
  234. Mutex::Lock _l(_lock);
  235. return _status();
  236. }
  237. /**
  238. * @param ec Buffer to fill with externally-visible network configuration
  239. */
  240. inline void externalConfig(ZT_VirtualNetworkConfig *ec) const
  241. {
  242. Mutex::Lock _l(_lock);
  243. _externalConfig(ec);
  244. }
  245. /**
  246. * Get current network config
  247. *
  248. * This returns a const reference to the network config in place, which is safe
  249. * to concurrently access but *may* change during access. Normally this isn't a
  250. * problem, but if it is use configCopy().
  251. *
  252. * @return Network configuration (may be a null config if we don't have one yet)
  253. */
  254. inline const NetworkConfig &config() const { return _config; }
  255. /**
  256. * @return A thread-safe copy of our NetworkConfig instead of a const reference
  257. */
  258. inline NetworkConfig configCopy() const
  259. {
  260. Mutex::Lock _l(_lock);
  261. return _config;
  262. }
  263. /**
  264. * @return True if this network has a valid config
  265. */
  266. inline bool hasConfig() const { return (_config); }
  267. /**
  268. * @return Ethernet MAC address for this network's local interface
  269. */
  270. inline const MAC &mac() const throw() { return _mac; }
  271. /**
  272. * Find the node on this network that has this MAC behind it (if any)
  273. *
  274. * @param mac MAC address
  275. * @return ZeroTier address of bridge to this MAC
  276. */
  277. inline Address findBridgeTo(const MAC &mac) const
  278. {
  279. Mutex::Lock _l(_lock);
  280. const Address *const br = _remoteBridgeRoutes.get(mac);
  281. if (br)
  282. return *br;
  283. return Address();
  284. }
  285. /**
  286. * Set a bridge route
  287. *
  288. * @param mac MAC address of destination
  289. * @param addr Bridge this MAC is reachable behind
  290. */
  291. void learnBridgeRoute(const MAC &mac,const Address &addr);
  292. /**
  293. * Learn a multicast group that is bridged to our tap device
  294. *
  295. * @param mg Multicast group
  296. * @param now Current time
  297. */
  298. void learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now);
  299. /**
  300. * Destroy this network
  301. *
  302. * This causes the network to disable itself, destroy its tap device, and on
  303. * delete to delete all trace of itself on disk and remove any persistent tap
  304. * device instances. Call this when a network is being removed from the system.
  305. */
  306. void destroy();
  307. /**
  308. * @return Pointer to user PTR (modifiable user ptr used in API)
  309. */
  310. inline void **userPtr() throw() { return &_uPtr; }
  311. inline bool operator==(const Network &n) const throw() { return (_id == n._id); }
  312. inline bool operator!=(const Network &n) const throw() { return (_id != n._id); }
  313. inline bool operator<(const Network &n) const throw() { return (_id < n._id); }
  314. inline bool operator>(const Network &n) const throw() { return (_id > n._id); }
  315. inline bool operator<=(const Network &n) const throw() { return (_id <= n._id); }
  316. inline bool operator>=(const Network &n) const throw() { return (_id >= n._id); }
  317. private:
  318. ZT_VirtualNetworkStatus _status() const;
  319. void _externalConfig(ZT_VirtualNetworkConfig *ec) const; // assumes _lock is locked
  320. bool _isAllowed(const SharedPtr<Peer> &peer) const;
  321. void _announceMulticastGroups();
  322. void _announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups) const;
  323. std::vector<MulticastGroup> _allMulticastGroups() const;
  324. const RuntimeEnvironment *RR;
  325. void *_uPtr;
  326. uint64_t _id;
  327. MAC _mac; // local MAC address
  328. volatile bool _portInitialized;
  329. std::vector< MulticastGroup > _myMulticastGroups; // multicast groups that we belong to (according to tap)
  330. Hashtable< MulticastGroup,uint64_t > _multicastGroupsBehindMe; // multicast groups that seem to be behind us and when we last saw them (if we are a bridge)
  331. Hashtable< MAC,Address > _remoteBridgeRoutes; // remote addresses where given MACs are reachable (for tracking devices behind remote bridges)
  332. NetworkConfig _config;
  333. volatile uint64_t _lastConfigUpdate;
  334. volatile bool _destroyed;
  335. enum {
  336. NETCONF_FAILURE_NONE,
  337. NETCONF_FAILURE_ACCESS_DENIED,
  338. NETCONF_FAILURE_NOT_FOUND,
  339. NETCONF_FAILURE_INIT_FAILED
  340. } _netconfFailure;
  341. volatile int _portError; // return value from port config callback
  342. Hashtable<Address,Membership> _memberships;
  343. Mutex _lock;
  344. AtomicCounter __refCount;
  345. };
  346. } // naemspace ZeroTier
  347. #endif