Network.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. Additional actions
  74. * such as TEE may be taken, and credentials may be pushed.
  75. *
  76. * @param noTee If true, do not TEE anything anywhere
  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, false if dropped or redirected
  86. */
  87. bool filterOutgoingPacket(
  88. const bool noTee,
  89. const Address &ztSource,
  90. const Address &ztDest,
  91. const MAC &macSource,
  92. const MAC &macDest,
  93. const uint8_t *frameData,
  94. const unsigned int frameLen,
  95. const unsigned int etherType,
  96. const unsigned int vlanId);
  97. /**
  98. * Apply filters to an incoming packet
  99. *
  100. * This applies filters from our network config and, if that doesn't match,
  101. * the peer's capabilities in ascending order of capability ID. If there is
  102. * a match certain actions may be taken such as sending a copy of the packet
  103. * to a TEE or REDIRECT target.
  104. *
  105. * @param sourcePeer Source Peer
  106. * @param ztDest Destination ZeroTier address
  107. * @param macSource Ethernet layer source address
  108. * @param macDest Ethernet layer destination address
  109. * @param frameData Ethernet frame data
  110. * @param frameLen Ethernet frame payload length
  111. * @param etherType 16-bit ethernet type ID
  112. * @param vlanId 16-bit VLAN ID
  113. * @return 0 == drop, 1 == accept, 2 == accept even if bridged
  114. */
  115. int filterIncomingPacket(
  116. const SharedPtr<Peer> &sourcePeer,
  117. const Address &ztDest,
  118. const MAC &macSource,
  119. const MAC &macDest,
  120. const uint8_t *frameData,
  121. const unsigned int frameLen,
  122. const unsigned int etherType,
  123. const unsigned int vlanId);
  124. /**
  125. * @return Network ID
  126. */
  127. inline uint64_t id() const throw() { return _id; }
  128. /**
  129. * @return Address of network's controller (most significant 40 bits of ID)
  130. */
  131. inline Address controller() const throw() { return Address(_id >> 24); }
  132. /**
  133. * @param nwid Network ID
  134. * @return Address of network's controller
  135. */
  136. static inline Address controllerFor(uint64_t nwid) throw() { return Address(nwid >> 24); }
  137. /**
  138. * @return Multicast group memberships for this network's port (local, not learned via bridging)
  139. */
  140. inline std::vector<MulticastGroup> multicastGroups() const
  141. {
  142. Mutex::Lock _l(_lock);
  143. return _myMulticastGroups;
  144. }
  145. /**
  146. * @return All multicast groups including learned groups that are behind any bridges we're attached to
  147. */
  148. inline std::vector<MulticastGroup> allMulticastGroups() const
  149. {
  150. Mutex::Lock _l(_lock);
  151. return _allMulticastGroups();
  152. }
  153. /**
  154. * @param mg Multicast group
  155. * @param includeBridgedGroups If true, also include any 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 mg New multicast group
  163. */
  164. void multicastSubscribe(const MulticastGroup &mg);
  165. /**
  166. * Unsubscribe from a multicast group
  167. *
  168. * @param mg Multicast group
  169. */
  170. void multicastUnsubscribe(const MulticastGroup &mg);
  171. /**
  172. * Announce multicast groups to a peer if that peer is authorized on this network
  173. *
  174. * @param peer Peer to try to announce multicast groups to
  175. * @return True if peer was authorized and groups were announced
  176. */
  177. bool tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer);
  178. /**
  179. * Apply a NetworkConfig to this network
  180. *
  181. * @param conf Configuration in NetworkConfig form
  182. * @return True if configuration was accepted
  183. */
  184. bool applyConfiguration(const NetworkConfig &conf);
  185. /**
  186. * Set or update this network's configuration
  187. *
  188. * @param nconf Network configuration
  189. * @param saveToDisk IF true (default), write config to disk
  190. * @return 0 -- rejected, 1 -- accepted but not new, 2 -- accepted new config
  191. */
  192. int setConfiguration(const NetworkConfig &nconf,bool saveToDisk);
  193. /**
  194. * Handle an inbound network config chunk
  195. *
  196. * Only chunks whose inRePacketId matches the packet ID of the last request
  197. * are handled. If this chunk completes the config, it is decoded and
  198. * setConfiguration() is called.
  199. *
  200. * @param inRePacketId In-re packet ID from OK(NETWORK_CONFIG_REQUEST)
  201. * @param data Chunk data
  202. * @param chunkSize Size of data[]
  203. * @param chunkIndex Index of chunk in full config
  204. * @param totalSize Total size of network config
  205. */
  206. void handleInboundConfigChunk(const uint64_t inRePacketId,const void *data,unsigned int chunkSize,unsigned int chunkIndex,unsigned int totalSize);
  207. /**
  208. * Set netconf failure to 'access denied' -- called in IncomingPacket when controller reports this
  209. */
  210. inline void setAccessDenied()
  211. {
  212. Mutex::Lock _l(_lock);
  213. _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
  214. }
  215. /**
  216. * Set netconf failure to 'not found' -- called by PacketDecider when controller reports this
  217. */
  218. inline void setNotFound()
  219. {
  220. Mutex::Lock _l(_lock);
  221. _netconfFailure = NETCONF_FAILURE_NOT_FOUND;
  222. }
  223. /**
  224. * Causes this network to request an updated configuration from its master node now
  225. *
  226. * There is a circuit breaker here to prevent this from being done more often
  227. * than once per second. This is to prevent things like NETWORK_CONFIG_REFRESH
  228. * from causing multiple requests.
  229. */
  230. void requestConfiguration();
  231. /**
  232. * @param peer Peer to check
  233. * @return True if peer is allowed to communicate on this network
  234. */
  235. inline bool isAllowed(const SharedPtr<Peer> &peer) const
  236. {
  237. Mutex::Lock _l(_lock);
  238. return _isAllowed(peer);
  239. }
  240. /**
  241. * Perform cleanup and possibly save state
  242. */
  243. void clean();
  244. /**
  245. * @return Time of last updated configuration or 0 if none
  246. */
  247. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  248. /**
  249. * @return Status of this network
  250. */
  251. inline ZT_VirtualNetworkStatus status() const
  252. {
  253. Mutex::Lock _l(_lock);
  254. return _status();
  255. }
  256. /**
  257. * @param ec Buffer to fill with externally-visible network configuration
  258. */
  259. inline void externalConfig(ZT_VirtualNetworkConfig *ec) const
  260. {
  261. Mutex::Lock _l(_lock);
  262. _externalConfig(ec);
  263. }
  264. /**
  265. * Get current network config
  266. *
  267. * This returns a const reference to the network config in place, which is safe
  268. * to concurrently access but *may* change during access. Normally this isn't a
  269. * problem, but if it is use configCopy().
  270. *
  271. * @return Network configuration (may be a null config if we don't have one yet)
  272. */
  273. inline const NetworkConfig &config() const { return _config; }
  274. /**
  275. * @return A thread-safe copy of our NetworkConfig instead of a const reference
  276. */
  277. inline NetworkConfig configCopy() const
  278. {
  279. Mutex::Lock _l(_lock);
  280. return _config;
  281. }
  282. /**
  283. * @return True if this network has a valid config
  284. */
  285. inline bool hasConfig() const { return (_config); }
  286. /**
  287. * @return Ethernet MAC address for this network's local interface
  288. */
  289. inline const MAC &mac() const throw() { return _mac; }
  290. /**
  291. * Find the node on this network that has this MAC behind it (if any)
  292. *
  293. * @param mac MAC address
  294. * @return ZeroTier address of bridge to this MAC
  295. */
  296. inline Address findBridgeTo(const MAC &mac) const
  297. {
  298. Mutex::Lock _l(_lock);
  299. const Address *const br = _remoteBridgeRoutes.get(mac);
  300. if (br)
  301. return *br;
  302. return Address();
  303. }
  304. /**
  305. * Set a bridge route
  306. *
  307. * @param mac MAC address of destination
  308. * @param addr Bridge this MAC is reachable behind
  309. */
  310. void learnBridgeRoute(const MAC &mac,const Address &addr);
  311. /**
  312. * Learn a multicast group that is bridged to our tap device
  313. *
  314. * @param mg Multicast group
  315. * @param now Current time
  316. */
  317. void learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now);
  318. /**
  319. * @param com Certificate of membership
  320. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  321. */
  322. inline int addCredential(const CertificateOfMembership &com)
  323. {
  324. if (com.networkId() != _id)
  325. return -1;
  326. Mutex::Lock _l(_lock);
  327. return _memberships[com.issuedTo()].addCredential(RR,com);
  328. }
  329. /**
  330. * @param cap Capability
  331. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  332. */
  333. inline int addCredential(const Capability &cap)
  334. {
  335. if (cap.networkId() != _id)
  336. return -1;
  337. Mutex::Lock _l(_lock);
  338. return _memberships[cap.issuedTo()].addCredential(RR,cap);
  339. }
  340. /**
  341. * @param cap Tag
  342. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  343. */
  344. inline int addCredential(const Tag &tag)
  345. {
  346. if (tag.networkId() != _id)
  347. return -1;
  348. Mutex::Lock _l(_lock);
  349. return _memberships[tag.issuedTo()].addCredential(RR,tag);
  350. }
  351. /**
  352. * Blacklist COM, tags, and capabilities before this time
  353. *
  354. * @param ts Blacklist cutoff
  355. */
  356. inline void blacklistBefore(const Address &peerAddress,const uint64_t ts)
  357. {
  358. Mutex::Lock _l(_lock);
  359. _memberships[peerAddress].blacklistBefore(ts);
  360. }
  361. /**
  362. * Destroy this network
  363. *
  364. * This causes the network to disable itself, destroy its tap device, and on
  365. * delete to delete all trace of itself on disk and remove any persistent tap
  366. * device instances. Call this when a network is being removed from the system.
  367. */
  368. void destroy();
  369. /**
  370. * @return Pointer to user PTR (modifiable user ptr used in API)
  371. */
  372. inline void **userPtr() throw() { return &_uPtr; }
  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. inline bool operator>=(const Network &n) const throw() { return (_id >= n._id); }
  379. private:
  380. ZT_VirtualNetworkStatus _status() const;
  381. void _externalConfig(ZT_VirtualNetworkConfig *ec) const; // assumes _lock is locked
  382. bool _isAllowed(const SharedPtr<Peer> &peer) const;
  383. void _announceMulticastGroups();
  384. void _announceMulticastGroupsTo(const SharedPtr<Peer> &peer,const std::vector<MulticastGroup> &allMulticastGroups);
  385. std::vector<MulticastGroup> _allMulticastGroups() const;
  386. const RuntimeEnvironment *RR;
  387. void *_uPtr;
  388. uint64_t _id;
  389. MAC _mac; // local MAC address
  390. volatile bool _portInitialized;
  391. std::vector< MulticastGroup > _myMulticastGroups; // multicast groups that we belong to (according to tap)
  392. Hashtable< MulticastGroup,uint64_t > _multicastGroupsBehindMe; // multicast groups that seem to be behind us and when we last saw them (if we are a bridge)
  393. Hashtable< MAC,Address > _remoteBridgeRoutes; // remote addresses where given MACs are reachable (for tracking devices behind remote bridges)
  394. uint64_t _inboundConfigPacketId;
  395. std::map<unsigned int,std::string> _inboundConfigChunks;
  396. NetworkConfig _config;
  397. volatile uint64_t _lastConfigUpdate;
  398. volatile uint64_t _lastRequestedConfiguration;
  399. volatile bool _destroyed;
  400. enum {
  401. NETCONF_FAILURE_NONE,
  402. NETCONF_FAILURE_ACCESS_DENIED,
  403. NETCONF_FAILURE_NOT_FOUND,
  404. NETCONF_FAILURE_INIT_FAILED
  405. } _netconfFailure;
  406. volatile int _portError; // return value from port config callback
  407. Hashtable<Address,Membership> _memberships;
  408. Mutex _lock;
  409. AtomicCounter __refCount;
  410. };
  411. } // naemspace ZeroTier
  412. #endif