Network.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_NETWORK_HPP
  27. #define ZT_NETWORK_HPP
  28. #include <stdint.h>
  29. #include "../include/ZeroTierOne.h"
  30. #include <string>
  31. #include <map>
  32. #include <vector>
  33. #include <algorithm>
  34. #include <stdexcept>
  35. #include "Constants.hpp"
  36. #include "NonCopyable.hpp"
  37. #include "Hashtable.hpp"
  38. #include "Address.hpp"
  39. #include "Mutex.hpp"
  40. #include "SharedPtr.hpp"
  41. #include "AtomicCounter.hpp"
  42. #include "MulticastGroup.hpp"
  43. #include "MAC.hpp"
  44. #include "Dictionary.hpp"
  45. #include "Multicaster.hpp"
  46. #include "Membership.hpp"
  47. #include "NetworkConfig.hpp"
  48. #include "CertificateOfMembership.hpp"
  49. #define ZT_NETWORK_MAX_INCOMING_UPDATES 3
  50. #define ZT_NETWORK_MAX_UPDATE_CHUNKS ((ZT_NETWORKCONFIG_DICT_CAPACITY / 1024) + 1)
  51. namespace ZeroTier {
  52. class RuntimeEnvironment;
  53. class Peer;
  54. /**
  55. * A virtual LAN
  56. */
  57. class Network : NonCopyable
  58. {
  59. friend class SharedPtr<Network>;
  60. public:
  61. /**
  62. * Broadcast multicast group: ff:ff:ff:ff:ff:ff / 0
  63. */
  64. static const MulticastGroup BROADCAST;
  65. /**
  66. * Compute primary controller device ID from network ID
  67. */
  68. static inline Address controllerFor(uint64_t nwid) throw() { return Address(nwid >> 24); }
  69. /**
  70. * Construct a new network
  71. *
  72. * Note that init() should be called immediately after the network is
  73. * constructed to actually configure the port.
  74. *
  75. * @param renv Runtime environment
  76. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  77. * @param nwid Network ID
  78. * @param uptr Arbitrary pointer used by externally-facing API (for user use)
  79. * @param nconf Network config, if known
  80. */
  81. Network(const RuntimeEnvironment *renv,void *tPtr,uint64_t nwid,void *uptr,const NetworkConfig *nconf);
  82. ~Network();
  83. inline uint64_t id() const { return _id; }
  84. inline Address controller() const { return Address(_id >> 24); }
  85. inline bool multicastEnabled() const { return (_config.multicastLimit > 0); }
  86. inline bool hasConfig() const { return (_config); }
  87. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  88. inline ZT_VirtualNetworkStatus status() const { Mutex::Lock _l(_lock); return _status(); }
  89. inline const NetworkConfig &config() const { return _config; }
  90. inline const MAC &mac() const { return _mac; }
  91. /**
  92. * Apply filters to an outgoing packet
  93. *
  94. * This applies filters from our network config and, if that doesn't match,
  95. * our capabilities in ascending order of capability ID. Additional actions
  96. * such as TEE may be taken, and credentials may be pushed, so this is not
  97. * side-effect-free. It's basically step one in sending something over VL2.
  98. *
  99. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  100. * @param noTee If true, do not TEE anything anywhere (for two-pass filtering as done with multicast and bridging)
  101. * @param ztSource Source ZeroTier address
  102. * @param ztDest Destination ZeroTier address
  103. * @param macSource Ethernet layer source address
  104. * @param macDest Ethernet layer destination address
  105. * @param frameData Ethernet frame data
  106. * @param frameLen Ethernet frame payload length
  107. * @param etherType 16-bit ethernet type ID
  108. * @param vlanId 16-bit VLAN ID
  109. * @return True if packet should be sent, false if dropped or redirected
  110. */
  111. bool filterOutgoingPacket(
  112. void *tPtr,
  113. const bool noTee,
  114. const Address &ztSource,
  115. const Address &ztDest,
  116. const MAC &macSource,
  117. const MAC &macDest,
  118. const uint8_t *frameData,
  119. const unsigned int frameLen,
  120. const unsigned int etherType,
  121. const unsigned int vlanId);
  122. /**
  123. * Apply filters to an incoming packet
  124. *
  125. * This applies filters from our network config and, if that doesn't match,
  126. * the peer's capabilities in ascending order of capability ID. If there is
  127. * a match certain actions may be taken such as sending a copy of the packet
  128. * to a TEE or REDIRECT target.
  129. *
  130. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  131. * @param sourcePeer Source Peer
  132. * @param ztDest Destination ZeroTier address
  133. * @param macSource Ethernet layer source address
  134. * @param macDest Ethernet layer destination address
  135. * @param frameData Ethernet frame data
  136. * @param frameLen Ethernet frame payload length
  137. * @param etherType 16-bit ethernet type ID
  138. * @param vlanId 16-bit VLAN ID
  139. * @return 0 == drop, 1 == accept, 2 == accept even if bridged
  140. */
  141. int filterIncomingPacket(
  142. void *tPtr,
  143. const SharedPtr<Peer> &sourcePeer,
  144. const Address &ztDest,
  145. const MAC &macSource,
  146. const MAC &macDest,
  147. const uint8_t *frameData,
  148. const unsigned int frameLen,
  149. const unsigned int etherType,
  150. const unsigned int vlanId);
  151. /**
  152. * Check whether we are subscribed to a multicast group
  153. *
  154. * @param mg Multicast group
  155. * @param includeBridgedGroups If true, also check groups we've learned via bridging
  156. * @return True if this network endpoint / peer is a member
  157. */
  158. bool subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const;
  159. /**
  160. * Subscribe to a multicast group
  161. *
  162. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  163. * @param mg New multicast group
  164. */
  165. void multicastSubscribe(void *tPtr,const MulticastGroup &mg);
  166. /**
  167. * Unsubscribe from a multicast group
  168. *
  169. * @param mg Multicast group
  170. */
  171. void multicastUnsubscribe(const MulticastGroup &mg);
  172. /**
  173. * Handle an inbound network config chunk
  174. *
  175. * This is called from IncomingPacket to handle incoming network config
  176. * chunks via OK(NETWORK_CONFIG_REQUEST) or NETWORK_CONFIG. It verifies
  177. * each chunk and once assembled applies the configuration.
  178. *
  179. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  180. * @param packetId Packet ID or 0 if none (e.g. via cluster path)
  181. * @param source Address of sender of chunk or NULL if none (e.g. via cluster path)
  182. * @param chunk Buffer containing chunk
  183. * @param ptr Index of chunk and related fields in packet
  184. * @return Update ID if update was fully assembled and accepted or 0 otherwise
  185. */
  186. uint64_t handleConfigChunk(void *tPtr,const uint64_t packetId,const Address &source,const Buffer<ZT_PROTO_MAX_PACKET_LENGTH> &chunk,unsigned int ptr);
  187. /**
  188. * Set network configuration
  189. *
  190. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  191. * @param nconf Network configuration
  192. * @param saveToDisk Save to disk? Used during loading, should usually be true otherwise.
  193. * @return 0 == bad, 1 == accepted but duplicate/unchanged, 2 == accepted and new
  194. */
  195. int setConfiguration(void *tPtr,const NetworkConfig &nconf,bool saveToDisk);
  196. /**
  197. * Set netconf failure to 'access denied' -- called in IncomingPacket when controller reports this
  198. */
  199. inline void setAccessDenied()
  200. {
  201. Mutex::Lock _l(_lock);
  202. _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
  203. }
  204. /**
  205. * Set netconf failure to 'not found' -- called by IncomingPacket when controller reports this
  206. */
  207. inline void setNotFound()
  208. {
  209. Mutex::Lock _l(_lock);
  210. _netconfFailure = NETCONF_FAILURE_NOT_FOUND;
  211. }
  212. /**
  213. * Causes this network to request an updated configuration from its master node now
  214. *
  215. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  216. */
  217. void requestConfiguration(void *tPtr);
  218. /**
  219. * Determine whether this peer is permitted to communicate on this network
  220. *
  221. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  222. * @param peer Peer to check
  223. */
  224. bool gate(void *tPtr,const SharedPtr<Peer> &peer);
  225. /**
  226. * Do periodic cleanup and housekeeping tasks
  227. */
  228. void clean();
  229. /**
  230. * Push state to members such as multicast group memberships and latest COM (if needed)
  231. *
  232. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  233. */
  234. inline void sendUpdatesToMembers(void *tPtr)
  235. {
  236. Mutex::Lock _l(_lock);
  237. _sendUpdatesToMembers(tPtr,(const MulticastGroup *)0);
  238. }
  239. /**
  240. * Find the node on this network that has this MAC behind it (if any)
  241. *
  242. * @param mac MAC address
  243. * @return ZeroTier address of bridge to this MAC
  244. */
  245. inline Address findBridgeTo(const MAC &mac) const
  246. {
  247. Mutex::Lock _l(_lock);
  248. const Address *const br = _remoteBridgeRoutes.get(mac);
  249. return ((br) ? *br : Address());
  250. }
  251. /**
  252. * Set a bridge route
  253. *
  254. * @param mac MAC address of destination
  255. * @param addr Bridge this MAC is reachable behind
  256. */
  257. void learnBridgeRoute(const MAC &mac,const Address &addr);
  258. /**
  259. * Learn a multicast group that is bridged to our tap device
  260. *
  261. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  262. * @param mg Multicast group
  263. * @param now Current time
  264. */
  265. void learnBridgedMulticastGroup(void *tPtr,const MulticastGroup &mg,uint64_t now);
  266. /**
  267. * Validate a credential and learn it if it passes certificate and other checks
  268. */
  269. Membership::AddCredentialResult addCredential(void *tPtr,const CertificateOfMembership &com);
  270. /**
  271. * Validate a credential and learn it if it passes certificate and other checks
  272. */
  273. inline Membership::AddCredentialResult addCredential(void *tPtr,const Capability &cap)
  274. {
  275. if (cap.networkId() != _id)
  276. return Membership::ADD_REJECTED;
  277. Mutex::Lock _l(_lock);
  278. return _membership(cap.issuedTo()).addCredential(RR,tPtr,_config,cap);
  279. }
  280. /**
  281. * Validate a credential and learn it if it passes certificate and other checks
  282. */
  283. inline Membership::AddCredentialResult addCredential(void *tPtr,const Tag &tag)
  284. {
  285. if (tag.networkId() != _id)
  286. return Membership::ADD_REJECTED;
  287. Mutex::Lock _l(_lock);
  288. return _membership(tag.issuedTo()).addCredential(RR,tPtr,_config,tag);
  289. }
  290. /**
  291. * Validate a credential and learn it if it passes certificate and other checks
  292. */
  293. Membership::AddCredentialResult addCredential(void *tPtr,const Address &sentFrom,const Revocation &rev);
  294. /**
  295. * Validate a credential and learn it if it passes certificate and other checks
  296. */
  297. inline Membership::AddCredentialResult addCredential(void *tPtr,const CertificateOfOwnership &coo)
  298. {
  299. if (coo.networkId() != _id)
  300. return Membership::ADD_REJECTED;
  301. Mutex::Lock _l(_lock);
  302. return _membership(coo.issuedTo()).addCredential(RR,tPtr,_config,coo);
  303. }
  304. /**
  305. * Force push credentials (COM, etc.) to a peer now
  306. *
  307. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  308. * @param to Destination peer address
  309. * @param now Current time
  310. */
  311. inline void pushCredentialsNow(void *tPtr,const Address &to,const uint64_t now)
  312. {
  313. Mutex::Lock _l(_lock);
  314. _membership(to).pushCredentials(RR,tPtr,now,to,_config,-1,true);
  315. }
  316. /**
  317. * Destroy this network
  318. *
  319. * This sets the network to completely remove itself on delete. This also prevents the
  320. * call of the normal port shutdown event on delete.
  321. */
  322. void destroy();
  323. /**
  324. * Get this network's config for export via the ZT core API
  325. *
  326. * @param ec Buffer to fill with externally-visible network configuration
  327. */
  328. inline void externalConfig(ZT_VirtualNetworkConfig *ec) const
  329. {
  330. Mutex::Lock _l(_lock);
  331. _externalConfig(ec);
  332. }
  333. /**
  334. * @return Externally usable pointer-to-pointer exported via the core API
  335. */
  336. inline void **userPtr() { return &_uPtr; }
  337. private:
  338. ZT_VirtualNetworkStatus _status() const;
  339. void _externalConfig(ZT_VirtualNetworkConfig *ec) const; // assumes _lock is locked
  340. bool _gate(const SharedPtr<Peer> &peer);
  341. void _sendUpdatesToMembers(void *tPtr,const MulticastGroup *const newMulticastGroup);
  342. void _announceMulticastGroupsTo(void *tPtr,const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups);
  343. std::vector<MulticastGroup> _allMulticastGroups() const;
  344. Membership &_membership(const Address &a);
  345. const RuntimeEnvironment *const RR;
  346. void *_uPtr;
  347. const uint64_t _id;
  348. uint64_t _lastAnnouncedMulticastGroupsUpstream;
  349. MAC _mac; // local MAC address
  350. bool _portInitialized;
  351. std::vector< MulticastGroup > _myMulticastGroups; // multicast groups that we belong to (according to tap)
  352. Hashtable< MulticastGroup,uint64_t > _multicastGroupsBehindMe; // multicast groups that seem to be behind us and when we last saw them (if we are a bridge)
  353. Hashtable< MAC,Address > _remoteBridgeRoutes; // remote addresses where given MACs are reachable (for tracking devices behind remote bridges)
  354. NetworkConfig _config;
  355. uint64_t _lastConfigUpdate;
  356. struct _IncomingConfigChunk
  357. {
  358. _IncomingConfigChunk() { memset(this,0,sizeof(_IncomingConfigChunk)); }
  359. uint64_t ts;
  360. uint64_t updateId;
  361. uint64_t haveChunkIds[ZT_NETWORK_MAX_UPDATE_CHUNKS];
  362. unsigned long haveChunks;
  363. unsigned long haveBytes;
  364. Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> data;
  365. };
  366. _IncomingConfigChunk _incomingConfigChunks[ZT_NETWORK_MAX_INCOMING_UPDATES];
  367. bool _destroyed;
  368. enum {
  369. NETCONF_FAILURE_NONE,
  370. NETCONF_FAILURE_ACCESS_DENIED,
  371. NETCONF_FAILURE_NOT_FOUND,
  372. NETCONF_FAILURE_INIT_FAILED
  373. } _netconfFailure;
  374. int _portError; // return value from port config callback
  375. Hashtable<Address,Membership> _memberships;
  376. Mutex _lock;
  377. AtomicCounter __refCount;
  378. };
  379. } // naemspace ZeroTier
  380. #endif