Network.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. * Handle an inbound network config chunk
  194. *
  195. * Only chunks whose inRePacketId matches the packet ID of the last request
  196. * are handled. If this chunk completes the config, it is decoded and
  197. * setConfiguration() is called.
  198. *
  199. * @param inRePacketId In-re packet ID from OK(NETWORK_CONFIG_REQUEST)
  200. * @param data Chunk data
  201. * @param chunkSize Size of data[]
  202. * @param chunkIndex Index of chunk in full config
  203. * @param totalSize Total size of network config
  204. */
  205. void handleInboundConfigChunk(const uint64_t inRePacketId,const void *data,unsigned int chunkSize,unsigned int chunkIndex,unsigned int totalSize);
  206. /**
  207. * Set netconf failure to 'access denied' -- called in IncomingPacket when controller reports this
  208. */
  209. inline void setAccessDenied()
  210. {
  211. Mutex::Lock _l(_lock);
  212. _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
  213. }
  214. /**
  215. * Set netconf failure to 'not found' -- called by PacketDecider when controller reports this
  216. */
  217. inline void setNotFound()
  218. {
  219. Mutex::Lock _l(_lock);
  220. _netconfFailure = NETCONF_FAILURE_NOT_FOUND;
  221. }
  222. /**
  223. * Causes this network to request an updated configuration from its master node now
  224. *
  225. * There is a circuit breaker here to prevent this from being done more often
  226. * than once per second. This is to prevent things like NETWORK_CONFIG_REFRESH
  227. * from causing multiple requests.
  228. */
  229. void requestConfiguration();
  230. /**
  231. * @param peer Peer to check
  232. * @return True if peer is allowed to communicate on this network
  233. */
  234. inline bool isAllowed(const SharedPtr<Peer> &peer) const
  235. {
  236. Mutex::Lock _l(_lock);
  237. return _isAllowed(peer);
  238. }
  239. /**
  240. * Perform cleanup and possibly save state
  241. */
  242. void clean();
  243. /**
  244. * @return Time of last updated configuration or 0 if none
  245. */
  246. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  247. /**
  248. * @return Status of this network
  249. */
  250. inline ZT_VirtualNetworkStatus status() const
  251. {
  252. Mutex::Lock _l(_lock);
  253. return _status();
  254. }
  255. /**
  256. * @param ec Buffer to fill with externally-visible network configuration
  257. */
  258. inline void externalConfig(ZT_VirtualNetworkConfig *ec) const
  259. {
  260. Mutex::Lock _l(_lock);
  261. _externalConfig(ec);
  262. }
  263. /**
  264. * Get current network config
  265. *
  266. * This returns a const reference to the network config in place, which is safe
  267. * to concurrently access but *may* change during access. Normally this isn't a
  268. * problem, but if it is use configCopy().
  269. *
  270. * @return Network configuration (may be a null config if we don't have one yet)
  271. */
  272. inline const NetworkConfig &config() const { return _config; }
  273. /**
  274. * @return A thread-safe copy of our NetworkConfig instead of a const reference
  275. */
  276. inline NetworkConfig configCopy() const
  277. {
  278. Mutex::Lock _l(_lock);
  279. return _config;
  280. }
  281. /**
  282. * @return True if this network has a valid config
  283. */
  284. inline bool hasConfig() const { return (_config); }
  285. /**
  286. * @return Ethernet MAC address for this network's local interface
  287. */
  288. inline const MAC &mac() const throw() { return _mac; }
  289. /**
  290. * Find the node on this network that has this MAC behind it (if any)
  291. *
  292. * @param mac MAC address
  293. * @return ZeroTier address of bridge to this MAC
  294. */
  295. inline Address findBridgeTo(const MAC &mac) const
  296. {
  297. Mutex::Lock _l(_lock);
  298. const Address *const br = _remoteBridgeRoutes.get(mac);
  299. if (br)
  300. return *br;
  301. return Address();
  302. }
  303. /**
  304. * Set a bridge route
  305. *
  306. * @param mac MAC address of destination
  307. * @param addr Bridge this MAC is reachable behind
  308. */
  309. void learnBridgeRoute(const MAC &mac,const Address &addr);
  310. /**
  311. * Learn a multicast group that is bridged to our tap device
  312. *
  313. * @param mg Multicast group
  314. * @param now Current time
  315. */
  316. void learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now);
  317. /**
  318. * @param com Certificate of membership
  319. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  320. */
  321. inline int addCredential(const CertificateOfMembership &com)
  322. {
  323. if (com.networkId() != _id)
  324. return -1;
  325. Mutex::Lock _l(_lock);
  326. return _memberships[com.issuedTo()].addCredential(RR,com);
  327. }
  328. /**
  329. * @param cap Capability
  330. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  331. */
  332. inline int addCredential(const Capability &cap)
  333. {
  334. if (cap.networkId() != _id)
  335. return -1;
  336. Mutex::Lock _l(_lock);
  337. return _memberships[cap.issuedTo()].addCredential(RR,cap);
  338. }
  339. /**
  340. * @param cap Tag
  341. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  342. */
  343. inline int addCredential(const Tag &tag)
  344. {
  345. if (tag.networkId() != _id)
  346. return -1;
  347. Mutex::Lock _l(_lock);
  348. return _memberships[tag.issuedTo()].addCredential(RR,tag);
  349. }
  350. /**
  351. * Blacklist COM, tags, and capabilities before this time
  352. *
  353. * @param ts Blacklist cutoff
  354. */
  355. inline void blacklistBefore(const Address &peerAddress,const uint64_t ts)
  356. {
  357. Mutex::Lock _l(_lock);
  358. _memberships[peerAddress].blacklistBefore(ts);
  359. }
  360. /**
  361. * Destroy this network
  362. *
  363. * This causes the network to disable itself, destroy its tap device, and on
  364. * delete to delete all trace of itself on disk and remove any persistent tap
  365. * device instances. Call this when a network is being removed from the system.
  366. */
  367. void destroy();
  368. /**
  369. * @return Pointer to user PTR (modifiable user ptr used in API)
  370. */
  371. inline void **userPtr() throw() { return &_uPtr; }
  372. inline bool operator==(const Network &n) const throw() { return (_id == n._id); }
  373. inline bool operator!=(const Network &n) const throw() { return (_id != n._id); }
  374. inline bool operator<(const Network &n) const throw() { return (_id < n._id); }
  375. inline bool operator>(const Network &n) const throw() { return (_id > n._id); }
  376. inline bool operator<=(const Network &n) const throw() { return (_id <= n._id); }
  377. inline bool operator>=(const Network &n) const throw() { return (_id >= n._id); }
  378. private:
  379. ZT_VirtualNetworkStatus _status() const;
  380. void _externalConfig(ZT_VirtualNetworkConfig *ec) const; // assumes _lock is locked
  381. bool _isAllowed(const SharedPtr<Peer> &peer) const;
  382. void _announceMulticastGroups();
  383. void _announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups);
  384. std::vector<MulticastGroup> _allMulticastGroups() const;
  385. const RuntimeEnvironment *RR;
  386. void *_uPtr;
  387. uint64_t _id;
  388. MAC _mac; // local MAC address
  389. volatile bool _portInitialized;
  390. std::vector< MulticastGroup > _myMulticastGroups; // multicast groups that we belong to (according to tap)
  391. Hashtable< MulticastGroup,uint64_t > _multicastGroupsBehindMe; // multicast groups that seem to be behind us and when we last saw them (if we are a bridge)
  392. Hashtable< MAC,Address > _remoteBridgeRoutes; // remote addresses where given MACs are reachable (for tracking devices behind remote bridges)
  393. uint64_t _inboundConfigPacketId;
  394. std::map<unsigned int,std::string> _inboundConfigChunks;
  395. NetworkConfig _config;
  396. volatile uint64_t _lastConfigUpdate;
  397. volatile uint64_t _lastRequestedConfiguration;
  398. volatile bool _destroyed;
  399. enum {
  400. NETCONF_FAILURE_NONE,
  401. NETCONF_FAILURE_ACCESS_DENIED,
  402. NETCONF_FAILURE_NOT_FOUND,
  403. NETCONF_FAILURE_INIT_FAILED
  404. } _netconfFailure;
  405. volatile int _portError; // return value from port config callback
  406. Hashtable<Address,Membership> _memberships;
  407. Mutex _lock;
  408. AtomicCounter __refCount;
  409. };
  410. } // naemspace ZeroTier
  411. #endif