Network.hpp 13 KB

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