Network.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. /**
  45. * A virtual LAN
  46. */
  47. class Network : NonCopyable
  48. {
  49. friend class SharedPtr<Network>;
  50. public:
  51. /**
  52. * Broadcast multicast group: ff:ff:ff:ff:ff:ff / 0
  53. */
  54. static const MulticastGroup BROADCAST;
  55. /**
  56. * Compute primary controller device ID from network ID
  57. */
  58. static inline Address controllerFor(uint64_t nwid) throw() { return Address(nwid >> 24); }
  59. /**
  60. * Construct a new network
  61. *
  62. * Note that init() should be called immediately after the network is
  63. * constructed to actually configure the port.
  64. *
  65. * @param renv Runtime environment
  66. * @param nwid Network ID
  67. * @param uptr Arbitrary pointer used by externally-facing API (for user use)
  68. */
  69. Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr);
  70. ~Network();
  71. inline uint64_t id() const { return _id; }
  72. inline Address controller() const { return Address(_id >> 24); }
  73. inline bool multicastEnabled() const { return (_config.multicastLimit > 0); }
  74. inline bool hasConfig() const { return (_config); }
  75. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  76. inline ZT_VirtualNetworkStatus status() const { Mutex::Lock _l(_lock); return _status(); }
  77. inline const NetworkConfig &config() const { return _config; }
  78. inline const MAC &mac() const { return _mac; }
  79. /**
  80. * Apply filters to an outgoing packet
  81. *
  82. * This applies filters from our network config and, if that doesn't match,
  83. * our capabilities in ascending order of capability ID. Additional actions
  84. * such as TEE may be taken, and credentials may be pushed, so this is not
  85. * side-effect-free. It's basically step one in sending something over VL2.
  86. *
  87. * @param noTee If true, do not TEE anything anywhere (for two-pass filtering as done with multicast and bridging)
  88. * @param ztSource Source ZeroTier address
  89. * @param ztDest Destination ZeroTier address
  90. * @param macSource Ethernet layer source address
  91. * @param macDest Ethernet layer destination address
  92. * @param frameData Ethernet frame data
  93. * @param frameLen Ethernet frame payload length
  94. * @param etherType 16-bit ethernet type ID
  95. * @param vlanId 16-bit VLAN ID
  96. * @return True if packet should be sent, false if dropped or redirected
  97. */
  98. bool filterOutgoingPacket(
  99. const bool noTee,
  100. const Address &ztSource,
  101. const Address &ztDest,
  102. const MAC &macSource,
  103. const MAC &macDest,
  104. const uint8_t *frameData,
  105. const unsigned int frameLen,
  106. const unsigned int etherType,
  107. const unsigned int vlanId);
  108. /**
  109. * Apply filters to an incoming packet
  110. *
  111. * This applies filters from our network config and, if that doesn't match,
  112. * the peer's capabilities in ascending order of capability ID. If there is
  113. * a match certain actions may be taken such as sending a copy of the packet
  114. * to a TEE or REDIRECT target.
  115. *
  116. * @param sourcePeer Source Peer
  117. * @param ztDest Destination ZeroTier address
  118. * @param macSource Ethernet layer source address
  119. * @param macDest Ethernet layer destination address
  120. * @param frameData Ethernet frame data
  121. * @param frameLen Ethernet frame payload length
  122. * @param etherType 16-bit ethernet type ID
  123. * @param vlanId 16-bit VLAN ID
  124. * @return 0 == drop, 1 == accept, 2 == accept even if bridged
  125. */
  126. int filterIncomingPacket(
  127. const SharedPtr<Peer> &sourcePeer,
  128. const Address &ztDest,
  129. const MAC &macSource,
  130. const MAC &macDest,
  131. const uint8_t *frameData,
  132. const unsigned int frameLen,
  133. const unsigned int etherType,
  134. const unsigned int vlanId);
  135. /**
  136. * Check whether we are subscribed to a multicast group
  137. *
  138. * @param mg Multicast group
  139. * @param includeBridgedGroups If true, also check groups we've learned via bridging
  140. * @return True if this network endpoint / peer is a member
  141. */
  142. bool subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const;
  143. /**
  144. * Subscribe to a multicast group
  145. *
  146. * @param mg New multicast group
  147. */
  148. void multicastSubscribe(const MulticastGroup &mg);
  149. /**
  150. * Unsubscribe from a multicast group
  151. *
  152. * @param mg Multicast group
  153. */
  154. void multicastUnsubscribe(const MulticastGroup &mg);
  155. /**
  156. * Handle an inbound network config chunk
  157. *
  158. * This is called from IncomingPacket when we receive a chunk from a network
  159. * controller.
  160. *
  161. * @param requestId An ID for grouping chunks, e.g. in-re packet ID for OK(NETWORK_CONFIG_REQUEST)
  162. * @param data Chunk data
  163. * @param chunkSize Size of data[]
  164. * @param chunkIndex Index of chunk in full config
  165. * @param totalSize Total size of network config
  166. */
  167. void handleInboundConfigChunk(const uint64_t requestId,const void *data,unsigned int chunkSize,unsigned int chunkIndex,unsigned int totalSize);
  168. /**
  169. * Set netconf failure to 'access denied' -- called in IncomingPacket when controller reports this
  170. */
  171. inline void setAccessDenied()
  172. {
  173. Mutex::Lock _l(_lock);
  174. _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
  175. }
  176. /**
  177. * Set netconf failure to 'not found' -- called by IncomingPacket when controller reports this
  178. */
  179. inline void setNotFound()
  180. {
  181. Mutex::Lock _l(_lock);
  182. _netconfFailure = NETCONF_FAILURE_NOT_FOUND;
  183. }
  184. /**
  185. * Causes this network to request an updated configuration from its master node now
  186. */
  187. void requestConfiguration();
  188. /**
  189. * Determine whether this peer is permitted to communicate on this network
  190. *
  191. * This also performs certain periodic actions such as pushing renewed
  192. * credentials to peers, so like the filters it is not side-effect-free.
  193. *
  194. * @param peer Peer to check
  195. * @param verb Packet verb
  196. * @param packetId Packet ID
  197. * @return True if peer is allowed to communicate on this network
  198. */
  199. bool gate(const SharedPtr<Peer> &peer,const Packet::Verb verb,const uint64_t packetId);
  200. /**
  201. * Check whether this peer is allowed to provide multicast info for this network
  202. */
  203. bool gateMulticastGatherReply(const SharedPtr<Peer> &peer,const Packet::Verb verb,const uint64_t packetId);
  204. /**
  205. * Do periodic cleanup and housekeeping tasks
  206. */
  207. void clean();
  208. /**
  209. * Push state to members such as multicast group memberships and latest COM (if needed)
  210. */
  211. inline void sendUpdatesToMembers()
  212. {
  213. Mutex::Lock _l(_lock);
  214. _sendUpdatesToMembers((const MulticastGroup *)0);
  215. }
  216. /**
  217. * Find the node on this network that has this MAC behind it (if any)
  218. *
  219. * @param mac MAC address
  220. * @return ZeroTier address of bridge to this MAC
  221. */
  222. inline Address findBridgeTo(const MAC &mac) const
  223. {
  224. Mutex::Lock _l(_lock);
  225. const Address *const br = _remoteBridgeRoutes.get(mac);
  226. return ((br) ? *br : Address());
  227. }
  228. /**
  229. * Set a bridge route
  230. *
  231. * @param mac MAC address of destination
  232. * @param addr Bridge this MAC is reachable behind
  233. */
  234. void learnBridgeRoute(const MAC &mac,const Address &addr);
  235. /**
  236. * Learn a multicast group that is bridged to our tap device
  237. *
  238. * @param mg Multicast group
  239. * @param now Current time
  240. */
  241. void learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now);
  242. /**
  243. * Validate a credential and learn it if it passes certificate and other checks
  244. */
  245. Membership::AddCredentialResult addCredential(const CertificateOfMembership &com);
  246. /**
  247. * Validate a credential and learn it if it passes certificate and other checks
  248. */
  249. inline Membership::AddCredentialResult addCredential(const Capability &cap)
  250. {
  251. if (cap.networkId() != _id)
  252. return Membership::ADD_REJECTED;
  253. Mutex::Lock _l(_lock);
  254. return _membership(cap.issuedTo()).addCredential(RR,_config,cap);
  255. }
  256. /**
  257. * Validate a credential and learn it if it passes certificate and other checks
  258. */
  259. inline Membership::AddCredentialResult addCredential(const Tag &tag)
  260. {
  261. if (tag.networkId() != _id)
  262. return Membership::ADD_REJECTED;
  263. Mutex::Lock _l(_lock);
  264. return _membership(tag.issuedTo()).addCredential(RR,_config,tag);
  265. }
  266. /**
  267. * Validate a credential and learn it if it passes certificate and other checks
  268. */
  269. Membership::AddCredentialResult addCredential(const Revocation &rev);
  270. /**
  271. * Force push credentials (COM, etc.) to a peer now
  272. *
  273. * @param to Destination peer address
  274. * @param now Current time
  275. */
  276. inline void pushCredentialsNow(const Address &to,const uint64_t now)
  277. {
  278. Mutex::Lock _l(_lock);
  279. _membership(to).pushCredentials(RR,now,to,_config,-1,true);
  280. }
  281. /**
  282. * Destroy this network
  283. *
  284. * This causes the network to disable itself, destroy its tap device, and on
  285. * delete to delete all trace of itself on disk and remove any persistent tap
  286. * device instances. Call this when a network is being removed from the system.
  287. */
  288. void destroy();
  289. /**
  290. * Get this network's config for export via the ZT core API
  291. *
  292. * @param ec Buffer to fill with externally-visible network configuration
  293. */
  294. inline void externalConfig(ZT_VirtualNetworkConfig *ec) const
  295. {
  296. Mutex::Lock _l(_lock);
  297. _externalConfig(ec);
  298. }
  299. /**
  300. * @return Externally usable pointer-to-pointer exported via the core API
  301. */
  302. inline void **userPtr() throw() { return &_uPtr; }
  303. private:
  304. int _setConfiguration(const NetworkConfig &nconf,bool saveToDisk);
  305. ZT_VirtualNetworkStatus _status() const;
  306. void _externalConfig(ZT_VirtualNetworkConfig *ec) const; // assumes _lock is locked
  307. bool _gate(const SharedPtr<Peer> &peer);
  308. void _sendUpdatesToMembers(const MulticastGroup *const newMulticastGroup);
  309. void _announceMulticastGroupsTo(const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups);
  310. std::vector<MulticastGroup> _allMulticastGroups() const;
  311. Membership &_membership(const Address &a);
  312. const RuntimeEnvironment *const RR;
  313. void *_uPtr;
  314. const uint64_t _id;
  315. uint64_t _lastAnnouncedMulticastGroupsUpstream;
  316. MAC _mac; // local MAC address
  317. volatile bool _portInitialized;
  318. std::vector< MulticastGroup > _myMulticastGroups; // multicast groups that we belong to (according to tap)
  319. Hashtable< MulticastGroup,uint64_t > _multicastGroupsBehindMe; // multicast groups that seem to be behind us and when we last saw them (if we are a bridge)
  320. Hashtable< MAC,Address > _remoteBridgeRoutes; // remote addresses where given MACs are reachable (for tracking devices behind remote bridges)
  321. uint64_t _inboundConfigPacketId;
  322. std::map<unsigned int,std::string> _inboundConfigChunks;
  323. NetworkConfig _config;
  324. volatile uint64_t _lastConfigUpdate;
  325. volatile bool _destroyed;
  326. enum {
  327. NETCONF_FAILURE_NONE,
  328. NETCONF_FAILURE_ACCESS_DENIED,
  329. NETCONF_FAILURE_NOT_FOUND,
  330. NETCONF_FAILURE_INIT_FAILED
  331. } _netconfFailure;
  332. volatile int _portError; // return value from port config callback
  333. Hashtable<Address,Membership> _memberships;
  334. Mutex _lock;
  335. AtomicCounter __refCount;
  336. };
  337. } // naemspace ZeroTier
  338. #endif