NetworkConfig.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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_NETWORKCONFIG_HPP
  19. #define ZT_NETWORKCONFIG_HPP
  20. #include <stdint.h>
  21. #include <string.h>
  22. #include <stdlib.h>
  23. #include <vector>
  24. #include <stdexcept>
  25. #include <algorithm>
  26. #include "../include/ZeroTierOne.h"
  27. #include "Constants.hpp"
  28. #include "Buffer.hpp"
  29. #include "InetAddress.hpp"
  30. #include "MulticastGroup.hpp"
  31. #include "Address.hpp"
  32. #include "CertificateOfMembership.hpp"
  33. #include "Dictionary.hpp"
  34. /**
  35. * Flag: allow passive bridging (experimental)
  36. */
  37. #define ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING 0x0000000000000001ULL
  38. /**
  39. * Flag: enable broadcast
  40. */
  41. #define ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST 0x0000000000000002ULL
  42. /**
  43. * Device is a network preferred relay
  44. */
  45. #define ZT_NETWORKCONFIG_SPECIALIST_TYPE_NETWORK_PREFERRED_RELAY 0x0000010000000000ULL
  46. /**
  47. * Device is an active bridge
  48. */
  49. #define ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE 0x0000020000000000ULL
  50. /**
  51. * An anchor is a device that is willing to be one and has been online/stable for a long time on this network
  52. */
  53. #define ZT_NETWORKCONFIG_SPECIALIST_TYPE_ANCHOR 0x0000040000000000ULL
  54. namespace ZeroTier {
  55. // Maximum size of a network config dictionary (can be increased)
  56. #define ZT_NETWORKCONFIG_DICT_CAPACITY 8194
  57. // Network config version
  58. #define ZT_NETWORKCONFIG_VERSION 6
  59. // Fields for meta-data sent with network config requests
  60. #define ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION "v"
  61. #define ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION "pv"
  62. #define ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION "majv"
  63. #define ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION "minv"
  64. #define ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION "revv"
  65. // These dictionary keys are short so they don't take up much room.
  66. // network config version
  67. #define ZT_NETWORKCONFIG_DICT_KEY_VERSION "v"
  68. // network ID
  69. #define ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID "nwid"
  70. // integer(hex)
  71. #define ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP "ts"
  72. // integer(hex)
  73. #define ZT_NETWORKCONFIG_DICT_KEY_REVISION "r"
  74. // address of member
  75. #define ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO "id"
  76. // flags(hex)
  77. #define ZT_NETWORKCONFIG_DICT_KEY_FLAGS "f"
  78. // integer(hex)
  79. #define ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_LIMIT "ml"
  80. // network type (hex)
  81. #define ZT_NETWORKCONFIG_DICT_KEY_TYPE "t"
  82. // text
  83. #define ZT_NETWORKCONFIG_DICT_KEY_NAME "n"
  84. // binary serialized certificate of membership
  85. #define ZT_NETWORKCONFIG_DICT_KEY_COM "C"
  86. // specialists (binary array of uint64_t)
  87. #define ZT_NETWORKCONFIG_DICT_KEY_SPECIALISTS "S"
  88. // routes (binary blob)
  89. #define ZT_NETWORKCONFIG_DICT_KEY_ROUTES "RT"
  90. // static IPs (binary blob)
  91. #define ZT_NETWORKCONFIG_DICT_KEY_STATIC_IPS "I"
  92. // pinned address physical route mappings (binary blob)
  93. #define ZT_NETWORKCONFIG_DICT_KEY_PINNED "P"
  94. // rules (binary blob)
  95. #define ZT_NETWORKCONFIG_DICT_KEY_RULES "R"
  96. // Legacy fields -- these are obsoleted but are included when older clients query
  97. // boolean (now a flag)
  98. #define ZT_NETWORKCONFIG_DICT_KEY_ALLOW_PASSIVE_BRIDGING_OLD "pb"
  99. // boolean (now a flag)
  100. #define ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST_OLD "eb"
  101. // IP/bits[,IP/bits,...]
  102. // Note that IPs that end in all zeroes are routes with no assignment in them.
  103. #define ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC_OLD "v4s"
  104. // IP/bits[,IP/bits,...]
  105. // Note that IPs that end in all zeroes are routes with no assignment in them.
  106. #define ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC_OLD "v6s"
  107. // 0/1
  108. #define ZT_NETWORKCONFIG_DICT_KEY_PRIVATE_OLD "p"
  109. // integer(hex)[,integer(hex),...]
  110. #define ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES_OLD "et"
  111. // string-serialized CertificateOfMembership
  112. #define ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP_OLD "com"
  113. // node[,node,...]
  114. #define ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES_OLD "ab"
  115. // node;IP/port[,node;IP/port]
  116. #define ZT_NETWORKCONFIG_DICT_KEY_RELAYS_OLD "rl"
  117. /**
  118. * Network configuration received from network controller nodes
  119. *
  120. * This is a memcpy()'able structure and is safe (in a crash sense) to modify
  121. * without locks.
  122. */
  123. class NetworkConfig
  124. {
  125. public:
  126. /**
  127. * Network preferred relay with optional physical endpoint addresses
  128. *
  129. * This is used by the convenience relays() method.
  130. */
  131. struct Relay
  132. {
  133. Address address;
  134. InetAddress phy4,phy6;
  135. };
  136. /**
  137. * Create an instance of a NetworkConfig for the test network ID
  138. *
  139. * The test network ID is defined as ZT_TEST_NETWORK_ID. This is a
  140. * "fake" network with no real controller and default options.
  141. *
  142. * @param self This node's ZT address
  143. * @return Configuration for test network ID
  144. */
  145. static inline NetworkConfig createTestNetworkConfig(const Address &self)
  146. {
  147. NetworkConfig nc;
  148. nc.networkId = ZT_TEST_NETWORK_ID;
  149. nc.timestamp = 1;
  150. nc.revision = 1;
  151. nc.issuedTo = self;
  152. nc.multicastLimit = ZT_MULTICAST_DEFAULT_LIMIT;
  153. nc.flags = ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  154. nc.type = ZT_NETWORK_TYPE_PUBLIC;
  155. nc.rules[0].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
  156. nc.ruleCount = 1;
  157. Utils::snprintf(nc.name,sizeof(nc.name),"ZT_TEST_NETWORK");
  158. // Make up a V4 IP from 'self' in the 10.0.0.0/8 range -- no
  159. // guarantee of uniqueness but collisions are unlikely.
  160. uint32_t ip = (uint32_t)((self.toInt() & 0x00ffffff) | 0x0a000000); // 10.x.x.x
  161. if ((ip & 0x000000ff) == 0x000000ff) ip ^= 0x00000001; // but not ending in .255
  162. if ((ip & 0x000000ff) == 0x00000000) ip ^= 0x00000001; // or .0
  163. nc.staticIps[0] = InetAddress(Utils::hton(ip),8);
  164. // Assign an RFC4193-compliant IPv6 address -- will never collide
  165. nc.staticIps[1] = InetAddress::makeIpv6rfc4193(ZT_TEST_NETWORK_ID,self.toInt());
  166. nc.staticIpCount = 2;
  167. return nc;
  168. }
  169. NetworkConfig()
  170. {
  171. memset(this,0,sizeof(NetworkConfig));
  172. }
  173. NetworkConfig(const NetworkConfig &nc)
  174. {
  175. memcpy(this,&nc,sizeof(NetworkConfig));
  176. }
  177. inline NetworkConfig &operator=(const NetworkConfig &nc)
  178. {
  179. memcpy(this,&nc,sizeof(NetworkConfig));
  180. return *this;
  181. }
  182. /**
  183. * @param etherType Ethernet frame type to check
  184. * @return True if allowed on this network
  185. */
  186. inline bool permitsEtherType(unsigned int etherType) const
  187. {
  188. unsigned int et = 0;
  189. for(unsigned int i=0;i<ruleCount;++i) {
  190. ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rules[i].t & 0x7f);
  191. if (rt == ZT_NETWORK_RULE_MATCH_ETHERTYPE) {
  192. et = rules[i].v.etherType;
  193. } else if (rt == ZT_NETWORK_RULE_ACTION_ACCEPT) {
  194. if ((!et)||(et == etherType))
  195. return true;
  196. et = 0;
  197. }
  198. }
  199. return false;
  200. }
  201. /**
  202. * Write this network config to a dictionary for transport
  203. *
  204. * @param d Dictionary
  205. * @param includeLegacy If true, include legacy fields for old node versions
  206. * @return True if dictionary was successfully created, false if e.g. overflow
  207. */
  208. bool toDictionary(Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> &d,bool includeLegacy) const;
  209. /**
  210. * Read this network config from a dictionary
  211. *
  212. * @param d Dictionary
  213. * @return True if dictionary was valid and network config successfully initialized
  214. */
  215. bool fromDictionary(const Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY> &d);
  216. /**
  217. * @return True if passive bridging is allowed (experimental)
  218. */
  219. inline bool allowPassiveBridging() const throw() { return ((this->flags & ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING) != 0); }
  220. /**
  221. * @return True if broadcast (ff:ff:ff:ff:ff:ff) address should work on this network
  222. */
  223. inline bool enableBroadcast() const throw() { return ((this->flags & ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST) != 0); }
  224. /**
  225. * @return Network type is public (no access control)
  226. */
  227. inline bool isPublic() const throw() { return (this->type == ZT_NETWORK_TYPE_PUBLIC); }
  228. /**
  229. * @return Network type is private (certificate access control)
  230. */
  231. inline bool isPrivate() const throw() { return (this->type == ZT_NETWORK_TYPE_PRIVATE); }
  232. /**
  233. * @return ZeroTier addresses of devices on this network designated as active bridges
  234. */
  235. inline std::vector<Address> activeBridges() const
  236. {
  237. std::vector<Address> r;
  238. for(unsigned int i=0;i<specialistCount;++i) {
  239. if ((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE) != 0)
  240. r.push_back(Address(specialists[i]));
  241. }
  242. return r;
  243. }
  244. /**
  245. * @return ZeroTier addresses of "anchor" devices on this network
  246. */
  247. inline std::vector<Address> anchors() const
  248. {
  249. std::vector<Address> r;
  250. for(unsigned int i=0;i<specialistCount;++i) {
  251. if ((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ANCHOR) != 0)
  252. r.push_back(Address(specialists[i]));
  253. }
  254. return r;
  255. }
  256. /**
  257. * Get pinned physical address for a given ZeroTier address, if any
  258. *
  259. * @param zt ZeroTier address
  260. * @param af Address family (e.g. AF_INET) or 0 for the first we find of any type
  261. * @return Physical address, if any
  262. */
  263. inline InetAddress findPinnedAddress(const Address &zt,unsigned int af) const
  264. {
  265. for(unsigned int i=0;i<pinnedCount;++i) {
  266. if (pinned[i].zt == zt) {
  267. if ((af == 0)||((unsigned int)pinned[i].phy.ss_family == af))
  268. return pinned[i].phy;
  269. }
  270. }
  271. return InetAddress();
  272. }
  273. /**
  274. * This gets network preferred relays with their static physical address if one is defined
  275. *
  276. * @return Network-preferred relays for this network (if none, only roots will be used)
  277. */
  278. inline std::vector<Relay> relays() const
  279. {
  280. std::vector<Relay> r;
  281. for(unsigned int i=0;i<specialistCount;++i) {
  282. if ((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_NETWORK_PREFERRED_RELAY) != 0) {
  283. r.push_back(Relay());
  284. r.back().address = specialists[i];
  285. r.back().phy4 = findPinnedAddress(r.back().address,AF_INET);
  286. r.back().phy6 = findPinnedAddress(r.back().address,AF_INET6);
  287. }
  288. }
  289. return r;
  290. }
  291. /**
  292. * @param fromPeer Peer attempting to bridge other Ethernet peers onto network
  293. * @return True if this network allows bridging
  294. */
  295. inline bool permitsBridging(const Address &fromPeer) const
  296. {
  297. if ((flags & ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING) != 0)
  298. return true;
  299. for(unsigned int i=0;i<specialistCount;++i) {
  300. if ((fromPeer == specialists[i])&&((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE) != 0))
  301. return true;
  302. }
  303. return false;
  304. }
  305. /**
  306. * Iterate through relays efficiently
  307. *
  308. * @param ptr Value-result parameter -- start by initializing with zero, then call until return is null
  309. * @return Address of relay or NULL if no more
  310. */
  311. Address nextRelay(unsigned int &ptr) const
  312. {
  313. while (ptr < specialistCount) {
  314. if ((specialists[ptr] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_NETWORK_PREFERRED_RELAY) != 0) {
  315. return Address(specialists[ptr]);
  316. }
  317. ++ptr;
  318. }
  319. return Address();
  320. }
  321. /**
  322. * @param zt ZeroTier address
  323. * @return True if this address is a relay
  324. */
  325. bool isRelay(const Address &zt) const
  326. {
  327. for(unsigned int i=0;i<specialistCount;++i) {
  328. if ((zt == specialists[i])&&((specialists[i] & ZT_NETWORKCONFIG_SPECIALIST_TYPE_NETWORK_PREFERRED_RELAY) != 0))
  329. return true;
  330. }
  331. return false;
  332. }
  333. /**
  334. * @return True if this network config is non-NULL
  335. */
  336. inline operator bool() const throw() { return (networkId != 0); }
  337. inline bool operator==(const NetworkConfig &nc) const { return (memcmp(this,&nc,sizeof(NetworkConfig)) == 0); }
  338. inline bool operator!=(const NetworkConfig &nc) const { return (!(*this == nc)); }
  339. /*
  340. inline void dump() const
  341. {
  342. printf("networkId==%.16llx\n",networkId);
  343. printf("timestamp==%llu\n",timestamp);
  344. printf("revision==%llu\n",revision);
  345. printf("issuedTo==%.10llx\n",issuedTo.toInt());
  346. printf("multicastLimit==%u\n",multicastLimit);
  347. printf("flags=%.8lx\n",(unsigned long)flags);
  348. printf("specialistCount==%u\n",specialistCount);
  349. for(unsigned int i=0;i<specialistCount;++i)
  350. printf(" specialists[%u]==%.16llx\n",i,specialists[i]);
  351. printf("routeCount==%u\n",routeCount);
  352. for(unsigned int i=0;i<routeCount;++i) {
  353. printf(" routes[i].target==%s\n",reinterpret_cast<const InetAddress *>(&(routes[i].target))->toString().c_str());
  354. printf(" routes[i].via==%s\n",reinterpret_cast<const InetAddress *>(&(routes[i].via))->toIpString().c_str());
  355. printf(" routes[i].flags==%.4x\n",(unsigned int)routes[i].flags);
  356. printf(" routes[i].metric==%u\n",(unsigned int)routes[i].metric);
  357. }
  358. printf("staticIpCount==%u\n",staticIpCount);
  359. for(unsigned int i=0;i<staticIpCount;++i)
  360. printf(" staticIps[i]==%s\n",staticIps[i].toString().c_str());
  361. printf("pinnedCount==%u\n",pinnedCount);
  362. for(unsigned int i=0;i<pinnedCount;++i) {
  363. printf(" pinned[i].zt==%s\n",pinned[i].zt.toString().c_str());
  364. printf(" pinned[i].phy==%s\n",pinned[i].phy.toString().c_str());
  365. }
  366. printf("ruleCount==%u\n",ruleCount);
  367. printf("name==%s\n",name);
  368. printf("com==%s\n",com.toString().c_str());
  369. }
  370. */
  371. /**
  372. * Add a specialist or mask flags if already present
  373. *
  374. * This masks the existing flags if the specialist is already here or adds
  375. * it otherwise.
  376. *
  377. * @param a Address of specialist
  378. * @param f Flags (OR of specialist role/type flags)
  379. * @return True if successfully masked or added
  380. */
  381. inline bool addSpecialist(const Address &a,const uint64_t f)
  382. {
  383. const uint64_t aint = a.toInt();
  384. for(unsigned int i=0;i<specialistCount;++i) {
  385. if ((specialists[i] & 0xffffffffffULL) == aint) {
  386. specialists[i] |= f;
  387. return true;
  388. }
  389. }
  390. if (specialistCount < ZT_MAX_NETWORK_SPECIALISTS) {
  391. specialists[specialistCount++] = f | aint;
  392. return true;
  393. }
  394. return false;
  395. }
  396. /**
  397. * Network ID that this configuration applies to
  398. */
  399. uint64_t networkId;
  400. /**
  401. * Controller-side time of config generation/issue
  402. */
  403. uint64_t timestamp;
  404. /**
  405. * Controller-side revision counter for this configuration
  406. */
  407. uint64_t revision;
  408. /**
  409. * Address of device to which this config is issued
  410. */
  411. Address issuedTo;
  412. /**
  413. * Flags (64-bit)
  414. */
  415. uint64_t flags;
  416. /**
  417. * Maximum number of recipients per multicast (not including active bridges)
  418. */
  419. unsigned int multicastLimit;
  420. /**
  421. * Number of specialists
  422. */
  423. unsigned int specialistCount;
  424. /**
  425. * Number of routes
  426. */
  427. unsigned int routeCount;
  428. /**
  429. * Number of ZT-managed static IP assignments
  430. */
  431. unsigned int staticIpCount;
  432. /**
  433. * Number of pinned devices (devices with physical address hints)
  434. */
  435. unsigned int pinnedCount;
  436. /**
  437. * Number of rule table entries
  438. */
  439. unsigned int ruleCount;
  440. /**
  441. * Specialist devices
  442. *
  443. * For each entry the least significant 40 bits are the device's ZeroTier
  444. * address and the most significant 24 bits are flags indicating its role.
  445. */
  446. uint64_t specialists[ZT_MAX_NETWORK_SPECIALISTS];
  447. /**
  448. * Statically defined "pushed" routes (including default gateways)
  449. */
  450. ZT_VirtualNetworkRoute routes[ZT_MAX_NETWORK_ROUTES];
  451. /**
  452. * Static IP assignments
  453. */
  454. InetAddress staticIps[ZT_MAX_ZT_ASSIGNED_ADDRESSES];
  455. /**
  456. * Pinned devices with physical address hints
  457. *
  458. * These can be used to specify a physical address where a given device
  459. * can be reached. It's usually used with network relays (specialists).
  460. */
  461. struct {
  462. Address zt;
  463. InetAddress phy;
  464. } pinned[ZT_MAX_NETWORK_PINNED];
  465. /**
  466. * Rules table
  467. */
  468. ZT_VirtualNetworkRule rules[ZT_MAX_NETWORK_RULES];
  469. /**
  470. * Network type (currently just public or private)
  471. */
  472. ZT_VirtualNetworkType type;
  473. /**
  474. * Network short name or empty string if not defined
  475. */
  476. char name[ZT_MAX_NETWORK_SHORT_NAME_LENGTH + 1];
  477. /**
  478. * Certficiate of membership (for private networks)
  479. */
  480. CertificateOfMembership com;
  481. };
  482. } // namespace ZeroTier
  483. #endif