Network.hpp 14 KB

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