Network.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. * Determine whether this peer is permitted to communicate on this network
  224. *
  225. * This also performs certain periodic actions such as pushing renewed
  226. * credentials to peers or requesting them if not present.
  227. *
  228. * @param peer Peer to check
  229. * @param verb Packet verb
  230. * @param packetId Packet ID
  231. * @return True if peer is allowed to communicate on this network
  232. */
  233. bool gate(const SharedPtr<Peer> &peer,const Packet::Verb verb,const uint64_t packetId);
  234. /**
  235. * Check whether this peer is allowed to provide multicast info for this network
  236. */
  237. bool gateMulticastGatherReply(const SharedPtr<Peer> &peer,const Packet::Verb verb,const uint64_t packetId);
  238. /**
  239. * Perform cleanup and possibly save state
  240. */
  241. void clean();
  242. /**
  243. * Push state to members such as multicast group memberships and latest COM (if needed)
  244. */
  245. inline void sendUpdatesToMembers()
  246. {
  247. Mutex::Lock _l(_lock);
  248. _sendUpdatesToMembers((const MulticastGroup *)0);
  249. }
  250. /**
  251. * @return Time of last updated configuration or 0 if none
  252. */
  253. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  254. /**
  255. * @return Status of this network
  256. */
  257. inline ZT_VirtualNetworkStatus status() const
  258. {
  259. Mutex::Lock _l(_lock);
  260. return _status();
  261. }
  262. /**
  263. * @param ec Buffer to fill with externally-visible network configuration
  264. */
  265. inline void externalConfig(ZT_VirtualNetworkConfig *ec) const
  266. {
  267. Mutex::Lock _l(_lock);
  268. _externalConfig(ec);
  269. }
  270. /**
  271. * Get current network config
  272. *
  273. * @return Network configuration (may be a null config if we don't have one yet)
  274. */
  275. inline const NetworkConfig &config() const { return _config; }
  276. /**
  277. * @return True if this network has a valid config
  278. */
  279. inline bool hasConfig() const { return (_config); }
  280. /**
  281. * @return Ethernet MAC address for this network's local interface
  282. */
  283. inline const MAC &mac() const { return _mac; }
  284. /**
  285. * Find the node on this network that has this MAC behind it (if any)
  286. *
  287. * @param mac MAC address
  288. * @return ZeroTier address of bridge to this MAC
  289. */
  290. inline Address findBridgeTo(const MAC &mac) const
  291. {
  292. Mutex::Lock _l(_lock);
  293. const Address *const br = _remoteBridgeRoutes.get(mac);
  294. return ((br) ? *br : Address());
  295. }
  296. /**
  297. * Set a bridge route
  298. *
  299. * @param mac MAC address of destination
  300. * @param addr Bridge this MAC is reachable behind
  301. */
  302. void learnBridgeRoute(const MAC &mac,const Address &addr);
  303. /**
  304. * Learn a multicast group that is bridged to our tap device
  305. *
  306. * @param mg Multicast group
  307. * @param now Current time
  308. */
  309. void learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now);
  310. /**
  311. * @param com Certificate of membership
  312. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  313. */
  314. int addCredential(const CertificateOfMembership &com);
  315. /**
  316. * @param cap Capability
  317. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  318. */
  319. inline int addCredential(const Capability &cap)
  320. {
  321. if (cap.networkId() != _id)
  322. return -1;
  323. Mutex::Lock _l(_lock);
  324. return _membership(cap.issuedTo()).addCredential(RR,cap);
  325. }
  326. /**
  327. * @param cap Tag
  328. * @return 0 == OK, 1 == waiting for WHOIS, -1 == BAD signature or credential
  329. */
  330. inline int addCredential(const Tag &tag)
  331. {
  332. if (tag.networkId() != _id)
  333. return -1;
  334. Mutex::Lock _l(_lock);
  335. return _membership(tag.issuedTo()).addCredential(RR,tag);
  336. }
  337. /**
  338. * Blacklist COM, tags, and capabilities before this time
  339. *
  340. * @param ts Blacklist cutoff
  341. */
  342. inline void blacklistBefore(const Address &peerAddress,const uint64_t ts)
  343. {
  344. Mutex::Lock _l(_lock);
  345. _membership(peerAddress).blacklistBefore(ts);
  346. }
  347. /**
  348. * Destroy this network
  349. *
  350. * This causes the network to disable itself, destroy its tap device, and on
  351. * delete to delete all trace of itself on disk and remove any persistent tap
  352. * device instances. Call this when a network is being removed from the system.
  353. */
  354. void destroy();
  355. /**
  356. * @return Pointer to user PTR (modifiable user ptr used in API)
  357. */
  358. inline void **userPtr() throw() { return &_uPtr; }
  359. private:
  360. ZT_VirtualNetworkStatus _status() const;
  361. void _externalConfig(ZT_VirtualNetworkConfig *ec) const; // assumes _lock is locked
  362. bool _gate(const SharedPtr<Peer> &peer);
  363. void _sendUpdatesToMembers(const MulticastGroup *const newMulticastGroup);
  364. void _announceMulticastGroupsTo(const Address &peer,const std::vector<MulticastGroup> &allMulticastGroups);
  365. std::vector<MulticastGroup> _allMulticastGroups() const;
  366. Membership &_membership(const Address &a);
  367. const RuntimeEnvironment *RR;
  368. void *_uPtr;
  369. uint64_t _id;
  370. uint64_t _lastAnnouncedMulticastGroupsUpstream;
  371. MAC _mac; // local MAC address
  372. volatile bool _portInitialized;
  373. std::vector< MulticastGroup > _myMulticastGroups; // multicast groups that we belong to (according to tap)
  374. Hashtable< MulticastGroup,uint64_t > _multicastGroupsBehindMe; // multicast groups that seem to be behind us and when we last saw them (if we are a bridge)
  375. Hashtable< MAC,Address > _remoteBridgeRoutes; // remote addresses where given MACs are reachable (for tracking devices behind remote bridges)
  376. uint64_t _inboundConfigPacketId;
  377. std::map<unsigned int,std::string> _inboundConfigChunks;
  378. NetworkConfig _config;
  379. volatile uint64_t _lastConfigUpdate;
  380. volatile uint64_t _lastRequestedConfiguration;
  381. volatile bool _destroyed;
  382. enum {
  383. NETCONF_FAILURE_NONE,
  384. NETCONF_FAILURE_ACCESS_DENIED,
  385. NETCONF_FAILURE_NOT_FOUND,
  386. NETCONF_FAILURE_INIT_FAILED
  387. } _netconfFailure;
  388. volatile int _portError; // return value from port config callback
  389. Hashtable<Address,Membership> _memberships;
  390. Mutex _lock;
  391. AtomicCounter __refCount;
  392. };
  393. } // naemspace ZeroTier
  394. #endif