Network.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. /**
  45. * A virtual LAN
  46. */
  47. class Network : NonCopyable
  48. {
  49. friend class SharedPtr<Network>;
  50. public:
  51. /**
  52. * Broadcast multicast group: ff:ff:ff:ff:ff:ff / 0
  53. */
  54. static const MulticastGroup BROADCAST;
  55. /**
  56. * Construct a new network
  57. *
  58. * Note that init() should be called immediately after the network is
  59. * constructed to actually configure the port.
  60. *
  61. * @param renv Runtime environment
  62. * @param nwid Network ID
  63. * @param uptr Arbitrary pointer used by externally-facing API (for user use)
  64. */
  65. Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr);
  66. ~Network();
  67. /**
  68. * Apply filters to an outgoing packet
  69. *
  70. * This applies filters from our network config and, if that doesn't match,
  71. * our capabilities in ascending order of capability ID. Additional actions
  72. * such as TEE may be taken, and credentials may be pushed.
  73. *
  74. * @param noTee If true, do not TEE anything anywhere
  75. * @param ztSource Source ZeroTier address
  76. * @param ztDest Destination ZeroTier address
  77. * @param macSource Ethernet layer source address
  78. * @param macDest Ethernet layer destination address
  79. * @param frameData Ethernet frame data
  80. * @param frameLen Ethernet frame payload length
  81. * @param etherType 16-bit ethernet type ID
  82. * @param vlanId 16-bit VLAN ID
  83. * @return True if packet should be sent, false if dropped or redirected
  84. */
  85. bool filterOutgoingPacket(
  86. const bool noTee,
  87. const Address &ztSource,
  88. const Address &ztDest,
  89. const MAC &macSource,
  90. const MAC &macDest,
  91. const uint8_t *frameData,
  92. const unsigned int frameLen,
  93. const unsigned int etherType,
  94. const unsigned int vlanId);
  95. /**
  96. * Apply filters to an incoming packet
  97. *
  98. * This applies filters from our network config and, if that doesn't match,
  99. * the peer's capabilities in ascending order of capability ID. If there is
  100. * a match certain actions may be taken such as sending a copy of the packet
  101. * to a TEE or REDIRECT target.
  102. *
  103. * @param sourcePeer Source Peer
  104. * @param ztDest Destination ZeroTier address
  105. * @param macSource Ethernet layer source address
  106. * @param macDest Ethernet layer destination address
  107. * @param frameData Ethernet frame data
  108. * @param frameLen Ethernet frame payload length
  109. * @param etherType 16-bit ethernet type ID
  110. * @param vlanId 16-bit VLAN ID
  111. * @return 0 == drop, 1 == accept, 2 == accept even if bridged
  112. */
  113. int filterIncomingPacket(
  114. const SharedPtr<Peer> &sourcePeer,
  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. * @return Network ID
  124. */
  125. inline uint64_t id() const throw() { return _id; }
  126. /**
  127. * @return Address of network's controller (most significant 40 bits of ID)
  128. */
  129. inline Address controller() const throw() { return Address(_id >> 24); }
  130. /**
  131. * @param nwid Network ID
  132. * @return Address of network's controller
  133. */
  134. static inline Address controllerFor(uint64_t nwid) throw() { return Address(nwid >> 24); }
  135. /**
  136. * @return Multicast group memberships for this network's port (local, not learned via bridging)
  137. */
  138. inline std::vector<MulticastGroup> multicastGroups() const
  139. {
  140. Mutex::Lock _l(_lock);
  141. return _myMulticastGroups;
  142. }
  143. /**
  144. * @return All multicast groups including learned groups that are behind any bridges we're attached to
  145. */
  146. inline std::vector<MulticastGroup> allMulticastGroups() const
  147. {
  148. Mutex::Lock _l(_lock);
  149. return _allMulticastGroups();
  150. }
  151. /**
  152. * @param mg Multicast group
  153. * @param includeBridgedGroups If true, also include any groups we've learned via bridging
  154. * @return True if this network endpoint / peer is a member
  155. */
  156. bool subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const;
  157. /**
  158. * Subscribe to a multicast group
  159. *
  160. * @param mg New multicast group
  161. */
  162. void multicastSubscribe(const MulticastGroup &mg);
  163. /**
  164. * Unsubscribe from a multicast group
  165. *
  166. * @param mg Multicast group
  167. */
  168. void multicastUnsubscribe(const MulticastGroup &mg);
  169. /**
  170. * Apply a NetworkConfig to this network
  171. *
  172. * @param conf Configuration in NetworkConfig form
  173. * @return True if configuration was accepted
  174. */
  175. bool applyConfiguration(const NetworkConfig &conf);
  176. /**
  177. * Set or update this network's configuration
  178. *
  179. * @param nconf Network configuration
  180. * @param saveToDisk IF true (default), write config to disk
  181. * @return 0 -- rejected, 1 -- accepted but not new, 2 -- accepted new config
  182. */
  183. int setConfiguration(const NetworkConfig &nconf,bool saveToDisk);
  184. /**
  185. * Handle an inbound network config chunk
  186. *
  187. * Only chunks whose inRePacketId matches the packet ID of the last request
  188. * are handled. If this chunk completes the config, it is decoded and
  189. * setConfiguration() is called.
  190. *
  191. * @param inRePacketId In-re packet ID from OK(NETWORK_CONFIG_REQUEST)
  192. * @param data Chunk data
  193. * @param chunkSize Size of data[]
  194. * @param chunkIndex Index of chunk in full config
  195. * @param totalSize Total size of network config
  196. */
  197. void handleInboundConfigChunk(const uint64_t inRePacketId,const void *data,unsigned int chunkSize,unsigned int chunkIndex,unsigned int totalSize);
  198. /**
  199. * Set netconf failure to 'access denied' -- called in IncomingPacket when controller reports this
  200. */
  201. inline void setAccessDenied()
  202. {
  203. Mutex::Lock _l(_lock);
  204. _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
  205. }
  206. /**
  207. * Set netconf failure to 'not found' -- called by PacketDecider when controller reports this
  208. */
  209. inline void setNotFound()
  210. {
  211. Mutex::Lock _l(_lock);
  212. _netconfFailure = NETCONF_FAILURE_NOT_FOUND;
  213. }
  214. /**
  215. * Causes this network to request an updated configuration from its master node now
  216. *
  217. * There is a circuit breaker here to prevent this from being done more often
  218. * than once per second. This is to prevent things like NETWORK_CONFIG_REFRESH
  219. * from causing multiple requests.
  220. */
  221. void requestConfiguration();
  222. /**
  223. * Membership check gate for incoming packets related to this network
  224. *
  225. * @param peer Peer to check
  226. * @param verb Packet verb
  227. * @param packetId Packet ID
  228. * @return True if peer is allowed to communicate on this network
  229. */
  230. bool gate(const SharedPtr<Peer> &peer,const Packet::Verb verb,const uint64_t packetId);
  231. /**
  232. * Check whether this peer is allowed to provide multicast info for this network
  233. */
  234. bool gateMulticastGatherReply(const SharedPtr<Peer> &peer,const Packet::Verb verb,const uint64_t packetId);
  235. /**
  236. * @param peer Peer to check
  237. * @return True if peer has recently been a valid member of this network
  238. */
  239. bool recentlyAllowedOnNetwork(const SharedPtr<Peer> &peer) const;
  240. /**
  241. * Perform cleanup and possibly save state
  242. */
  243. void clean();
  244. /**
  245. * Push state to members such as multicast group memberships and latest COM (if needed)
  246. */
  247. inline void sendUpdatesToMembers()
  248. {
  249. Mutex::Lock _l(_lock);
  250. _sendUpdatesToMembers((const MulticastGroup *)0);
  251. }
  252. /**
  253. * @return Time of last updated configuration or 0 if none
  254. */
  255. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  256. /**
  257. * @return Status of this network
  258. */
  259. inline ZT_VirtualNetworkStatus status() const
  260. {
  261. Mutex::Lock _l(_lock);
  262. return _status();
  263. }
  264. /**
  265. * @param ec Buffer to fill with externally-visible network configuration
  266. */
  267. inline void externalConfig(ZT_VirtualNetworkConfig *ec) const
  268. {
  269. Mutex::Lock _l(_lock);
  270. _externalConfig(ec);
  271. }
  272. /**
  273. * Get current network config
  274. *
  275. * @return Network configuration (may be a null config if we don't have one yet)
  276. */
  277. inline const NetworkConfig &config() const { return _config; }
  278. /**
  279. * @return True if this network has a valid config
  280. */
  281. inline bool hasConfig() const { return (_config); }
  282. /**
  283. * @return Ethernet MAC address for this network's local interface
  284. */
  285. inline const MAC &mac() const { return _mac; }
  286. /**
  287. * Find the node on this network that has this MAC behind it (if any)
  288. *
  289. * @param mac MAC address
  290. * @return ZeroTier address of bridge to this MAC
  291. */
  292. inline Address findBridgeTo(const MAC &mac) const
  293. {
  294. Mutex::Lock _l(_lock);
  295. const Address *const br = _remoteBridgeRoutes.get(mac);
  296. return ((br) ? *br : Address());
  297. }
  298. /**
  299. * Set a bridge route
  300. *
  301. * @param mac MAC address of destination
  302. * @param addr Bridge this MAC is reachable behind
  303. */
  304. void learnBridgeRoute(const MAC &mac,const Address &addr);
  305. /**
  306. * Learn a multicast group that is bridged to our tap device
  307. *
  308. * @param mg Multicast group
  309. * @param now Current time
  310. */
  311. void learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now);
  312. /**
  313. * @param com Certificate of membership
  314. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  315. */
  316. int addCredential(const CertificateOfMembership &com);
  317. /**
  318. * @param cap Capability
  319. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  320. */
  321. inline int addCredential(const Capability &cap)
  322. {
  323. if (cap.networkId() != _id)
  324. return -1;
  325. Mutex::Lock _l(_lock);
  326. return _membership(cap.issuedTo()).addCredential(RR,cap);
  327. }
  328. /**
  329. * @param cap Tag
  330. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  331. */
  332. inline int addCredential(const Tag &tag)
  333. {
  334. if (tag.networkId() != _id)
  335. return -1;
  336. Mutex::Lock _l(_lock);
  337. return _membership(tag.issuedTo()).addCredential(RR,tag);
  338. }
  339. /**
  340. * Blacklist COM, tags, and capabilities before this time
  341. *
  342. * @param ts Blacklist cutoff
  343. */
  344. inline void blacklistBefore(const Address &peerAddress,const uint64_t ts)
  345. {
  346. Mutex::Lock _l(_lock);
  347. _membership(peerAddress).blacklistBefore(ts);
  348. }
  349. /**
  350. * Destroy this network
  351. *
  352. * This causes the network to disable itself, destroy its tap device, and on
  353. * delete to delete all trace of itself on disk and remove any persistent tap
  354. * device instances. Call this when a network is being removed from the system.
  355. */
  356. void destroy();
  357. /**
  358. * @return Pointer to user PTR (modifiable user ptr used in API)
  359. */
  360. inline void **userPtr() throw() { return &_uPtr; }
  361. private:
  362. ZT_VirtualNetworkStatus _status() const;
  363. void _externalConfig(ZT_VirtualNetworkConfig *ec) const; // assumes _lock is locked
  364. bool _gate(const SharedPtr<Peer> &peer);
  365. void _sendUpdatesToMembers(const MulticastGroup *const newMulticastGroup);
  366. void _announceMulticastGroupsTo(const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups);
  367. std::vector<MulticastGroup> _allMulticastGroups() const;
  368. Membership &_membership(const Address &a);
  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